溫馨提示×

如何在java script中使用模塊

小樊
107
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女