模組系統 (Module System)#

模組(Module)是 Node.js 組織程式碼的基本單位。每個 .js 檔案都是一個獨立的模組,可以匯出(export)自己的功能,也可以匯入(import)其他模組的功能,讓程式碼更容易維護與重用。

Node.js 支援兩種模組系統:CommonJS(傳統)與 ESM(ECMAScript Modules)(現代)。


1. CommonJS(CJS)#

CommonJS 是 Node.js 最早使用的模組系統,使用 require() 匯入、module.exports 匯出。

匯出#

建立 math.js

1
2
3
4
5
6
7
8
9
function add(a, b) {
    return a + b;
}

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

module.exports = { add, subtract };

匯入#

建立 main.js

1
2
3
4
const math = require("./math");

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

也可以用解構賦值直接取出需要的函數:

1
2
3
const { add, subtract } = require("./math");

console.log(add(10, 5)); // 15

2. ESM(ECMAScript Modules)#

ESM 是現代 JavaScript 的標準模組系統,使用 import / export 語法。

要在 Node.js 使用 ESM,有兩種方式:

  1. 將檔案副檔名改為 .mjs
  2. package.json 加入 "type": "module"

匯出#

建立 math.mjs

1
2
3
4
5
6
7
export function add(a, b) {
    return a + b;
}

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

匯入#

建立 main.mjs

1
2
3
4
import { add, subtract } from "./math.mjs";

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

3. 預設匯出(Default Export)#

每個模組可以有一個預設匯出,匯入時可自訂名稱。

1
2
3
4
// greeter.mjs
export default function greet(name) {
    return `Hello, ${name}!`;
}
1
2
3
4
// main.mjs
import greet from "./greeter.mjs";

console.log(greet("Node.js")); // Hello, Node.js!

4. CJS vs ESM 比較#

特性CommonJS (CJS)ESM
語法require / module.exportsimport / export
載入時機執行期(動態)解析期(靜態)
副檔名.js.mjs 或設定 "type": "module"
適用場景舊版 Node.js 專案現代專案推薦

Reference#