JavaScript(8):ES module 匯入與匯出

Blog背景圖

早期模塊化規範-CommonJS(CJS)

運行環境: 主要在Node.js環境下運行。Node.js是一個基於V8引擎的伺服器端JavaScript執行環境,並且內建支援CommonJS模塊系統。

  • 匯入模塊
    使用require語法進行模塊匯入
  • 匯出模塊
    使用module.exportsexports語法進行模塊匯出

  • 以下是匯出的JS檔案(Export.js)
1
2
3
4
5
6
7
// ↓匯出變數
exports.myVariable = "Hello from CommonJS";

// ↓匯出函數
module.exports.myVariableFunc = function(Value){
return Value + 100
}
  • 以下是匯入的JS檔案(Import.js)
1
2
3
4
5
6
// ↓匯入模塊
const myModule = require('./Export.js');

console.log("myModule", myModule)
console.log("myVariable", myModule.myVariable)
console.log("myVariableFunc", myModule.myVariableFunc(200))

顯示如下:

1
2
3
4
5
6
myModule {
myVariable: 'Hello from CommonJS',
myVariableFunc: [Function (anonymous)]
}
myVariable Hello from CommonJS
myVariableFunc 300

ES6模塊化規範-ES Module(ESM)

運行環境: 可以在Node.js瀏覽器環境下運行。ES Modules是ECMAScript 6(ES6)引入的官方模塊系統,得到了現代瀏覽器的原生支援。

  • 匯入模塊
    使用import語法進行模塊匯入
  • 匯出模塊
    使用export語法進行模塊匯出

方式分為以下兩種

具名匯出(Named Export)

  • 藉由解構賦值來選擇性地引入模塊中的特定變數、函數或類別。
  • 模塊可同時匯出多個變數、函數或類別,使得模塊的功能可以被彈性地引入。
  • 匯入的變數名稱必須與原始模塊中的名稱保持一致

  • 以下是匯出的JS檔案(Export.js)
1
2
3
4
5
6
7
// ↓具名匯出變數
export const myVariable = "Hello from ES Module";

// ↓具名匯出函數
export function myFunction(Value) {
return Value + 100
};
  • 以下是匯入的JS檔案(Import.js)
1
2
3
4
5
// ↓具名匯入 (Named Import)
import { myVariable, myFunction } from './Export.js';

console.log("myVariable", myVariable)
console.log("myFunction", myFunction(300))

顯示如下

1
2
myVariable Hello from ES Module
myFunction 400

匯出的JS檔案不同的寫法(統一最後在匯出)

1
2
3
4
5
6
7
8
9
// ↓具名匯出變數
const myVariable = "Hello from ES Module";

// ↓具名匯出函數
function myFunction(Value) {
return Value + 100
};

export { myVariable, myFunction }

匯入所有的具名模塊(*)

  • 需要將*命名成一個自定義的對象名稱
1
2
3
4
5
6
// ↓具名匯入 (Named Import)
import * as importModule from './Export.js';

console.log("importModule", importModule)
console.log("myVariable", importModule.myVariable)
console.log("myFunction", importModule.myFunction(300))

顯示如下

1
2
3
4
5
6
importModule [Module: null prototype] {
myFunction: [Function: myFunction],
myVariable: 'Hello from ES Module'
}
myVariable Hello from ES Module
myFunction 400

預設匯出(Default Export)

  • 模塊中唯一的默認導出。每個模塊只能使用一個 export default 來導出一個變數、函數、物件等。
  • 可以自行命名引入的變數名稱

  • 以下是匯出的JS檔案(Export.js)
1
2
3
// ↓預設匯出變數
const defaultVariable = "Hello from Default Export";
export default defaultVariable;
  • 以下是匯入的JS檔案(Import.js)
1
2
3
4
// ↓具名匯入 (Named Import)
import Customize from './Export.js';

console.log("Customize", Customize)

模塊化使用教學

Nodejs

  • 透過以下語法快速生成專案所需的package.json
1
npm init -y
  • 新增type告訴專案使用的是commonjs或是module即可使用對應的方法。
    Package.json設定照片

瀏覽器

使用自己撰寫的js方法

  • 透過VS Code Live Server或是自幾架設Server(避免CORS限制)
  • Export.js檔案內容如下
1
2
3
4
5
6
7
8
9
// ↓具名匯出變數
const myVariable = "Hello from ES Module";

// ↓具名匯出函數
function myFunction(Value) {
return Value + 100
};

export { myVariable, myFunction }
  • 以下是HTML範例檔案
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES Module Example</title>
</head>

<body>
<script type="module">
import { myVariable, myFunction } from './Export.js'
console.log(myFunction(800))
</script>
</body>

</html>

顯示結果如下:
ESM匯入自己的JS方法

使用第三方套件的JS方法

  • 透過CDN的網站查找別人已開發好的第三方套件方法
  • 網站連結
  • 需確認CDN上面有寫esm標記,代表可以使用ECMAScript模塊的方式匯入
    確定CDN有esm的標記

  • 範例如下(以Axios為例)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Using Axios in the Browser</title>
</head>

<body>
<script type="module">
import axios from 'https://cdnjs.cloudflare.com/ajax/libs/axios/1.6.2/esm/axios.js';
// 發送 GET 請求
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
console.log('Data:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
</script>
</body>

</html>

顯示如下
ESM使用Axios第三方套件