JavaScript:ES module 匯入與匯出
2.9k 字,約 3 分鐘
文章目錄
早期模塊化規範-CommonJS(CJS)
運行環境: 主要在Node.js環境下運行。Node.js 是一個基於 V8 引擎的伺服器端 JavaScript 執行環境,並且內建支援 CommonJS 模塊系統。
- 匯入模塊 使用require語法進行模塊匯入
- 匯出模塊 使用module.exports或exports語法進行模塊匯出
- 以下是匯出的 JS 檔案(Export.js)
// ↓匯出變數
exports.myVariable = "Hello from CommonJS";
// ↓匯出函數
module.exports.myVariableFunc = function(Value){
return Value + 100
}
- 以下是匯入的 JS 檔案(Import.js)
// ↓匯入模塊
const myModule = require('./Export.js');
console.log("myModule", myModule)
console.log("myVariable", myModule.myVariable)
console.log("myVariableFunc", myModule.myVariableFunc(200))
顯示如下:
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)
// ↓具名匯出變數
export const myVariable = "Hello from ES Module";
// ↓具名匯出函數
export function myFunction(Value) {
return Value + 100
};
- 以下是匯入的 JS 檔案(Import.js)
// ↓具名匯入 (Named Import)
import { myVariable, myFunction } from './Export.js';
console.log("myVariable", myVariable)
console.log("myFunction", myFunction(300))
顯示如下
myVariable Hello from ES Module
myFunction 400
匯出的 JS 檔案不同的寫法(統一最後在匯出)
// ↓具名匯出變數
const myVariable = "Hello from ES Module";
// ↓具名匯出函數
function myFunction(Value) {
return Value + 100
};
export { myVariable, myFunction }
匯入所有的具名模塊(*)
- 需要將*命名成一個自定義的對象名稱
// ↓具名匯入 (Named Import)
import * as importModule from './Export.js';
console.log("importModule", importModule)
console.log("myVariable", importModule.myVariable)
console.log("myFunction", importModule.myFunction(300))
顯示如下
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)
// ↓預設匯出變數
const defaultVariable = "Hello from Default Export";
export default defaultVariable;
- 以下是匯入的 JS 檔案(Import.js)
// ↓具名匯入 (Named Import)
import Customize from './Export.js';
console.log("Customize", Customize)
模塊化使用教學
Nodejs
- 透過以下語法快速生成專案所需的 package.json
npm init -y
- 新增 type 告訴專案使用的是 commonjs 或是 module 即可使用對應的方法。
瀏覽器
使用自己撰寫的 js 方法
- 透過 VS Code Live Server 或是自幾架設 Server(避免 CORS 限制)
- Export.js 檔案內容如下
// ↓具名匯出變數
const myVariable = "Hello from ES Module";
// ↓具名匯出函數
function myFunction(Value) {
return Value + 100
};
export { myVariable, myFunction }
- 以下是 HTML 範例檔案
<!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>
顯示結果如下:
使用第三方套件的 JS 方法
- 透過 CDN 的網站查找別人已開發好的第三方套件方法
- 網站連結
- 需確認 CDN 上面有寫 esm 標記,代表可以使用 ECMAScript 模塊的方式匯入
- 範例如下(以 Axios 為例)
<!-- 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>
顯示如下
留言
留言使用 GitHub 帳號登入(Giscus),留言會存在 GitHub Discussions。