温馨提示×

如何在java script中使用模块

小樊
81
2024-06-27 20:50:23
栏目: 编程语言

在 JavaScript 中使用模块通常有两种方式:CommonJS 和 ES6 模块。

  1. 使用 CommonJS 模块: 在 Node.js 等环境中,可以使用 CommonJS 模块来导入和导出模块。 导出模块:
// math.js
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

module.exports = {
  add,
  subtract
}

导入模块:

// index.js
const math = require('./math');

console.log(math.add(1, 2)); // 输出 3
console.log(math.subtract(5, 3)); // 输出 2
  1. 使用 ES6 模块: 在现代浏览器中,可以使用 ES6 模块来导入和导出模块。 导出模块:
// math.js
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

导入模块:

// index.js
import { add, subtract } from './math';

console.log(add(1, 2)); // 输出 3
console.log(subtract(5, 3)); // 输出 2

需要注意的是,浏览器中使用 ES6 模块时,需要在 script 标签中添加 type=“module” 属性。例如:

<script type="module" src="index.js"></script>

总的来说,使用 ES6 模块可以让代码更加清晰和模块化,推荐在现代项目中使用 ES6 模块。

0