# 模組語法 在 JavaScript 中主要有兩種類型: - CommonJS - ES 模組(ESM)。 >兩者在模組匯入和匯出的語法上有一些差異,且支援的環境和特性也不同。 ### CommonJS 模組語法 CommonJS 是 Node.js 最早使用的模組系統,通常用於 Node.js 環境。它使用 require 來匯入模組,用 module.exports 或 exports 來匯出模組。 - 匯入模組: ```javascript= const fs = require('fs'); const path = require('path'); ``` - 匯出模組: ```javascript= // 使用 module.exports module.exports = { foo: function() { console.log('foo'); } }; // 或者使用 exports exports.bar = function() { console.log('bar'); }; ``` 優點: : - 廣泛支援於 Node.js 環境。 - 即使在舊版 Node.js 中也能使用。 缺點 : - 不支援靜態分析和樹損壞(Tree Shaking)。 - ES 模組語法 (ESM) - ES 模組是 ECMAScript 6(ES6)標準化的模組系統,現代 JavaScript 瀏覽器和 Node.js(從 v12.17.0 起)都支援。 --- ### ES 模組語法 (ESM) ES 模組是 ECMAScript 6(ES6)標準化的模組系統,現代 JavaScript 瀏覽器和 Node.js(從 v12.17.0 起)都支援。 - 匯入模組: ```javascript= import fs from 'fs'; import { join } from 'path'; ``` - 匯出模組: ```javascript= // 匯出多個成員 export function foo() { console.log('foo'); } export function bar() { console.log('bar'); } // 匯出預設成員 export default function() { console.log('default export'); } ``` 優點 : - 支援靜態分析,有助於工具如 Tree Shaking 來移除未使用的代碼。 - 語法更接近於現代 JavaScript 標準。 缺點 : - 在某些舊環境中可能不被支援,需要 Babel 或類似工具進行轉譯。 - 需要在 Node.js 中進行額外配置(例如,在 package.json 中設置 "type": "module")。 --- # Node.js 中使用 ES 模組: 確保在 package.json 中設置 "type": "module",然後使用 .mjs 文件擴展名或者在 .js 文件中使用 ES 模組語法: json 複製程式碼 { "type": "module" } 範例: module.mjs: javascript 複製程式碼 export function greet(name) { console.log(`Hello, ${name}`); } index.mjs: javascript 複製程式碼 import { greet } from './module.mjs'; greet('World'); 或者,在 .js 文件中: module.js: javascript 複製程式碼 export function greet(name) { console.log(`Hello, ${name}`); } index.js: javascript 複製程式碼 import { greet } from './module.js'; greet('World'); 選擇使用哪種語法 Node.js 環境: 如果需要支援較舊版本的 Node.js 或者模組是用於廣泛的社區共享,使用 CommonJS。 如果專案是現代化的並且使用了最新的 Node.js 版本,建議使用 ES 模組。 瀏覽器環境: 現代瀏覽器已經全面支援 ES 模組,因此應該使用 ES 模組語法。 如果需要支援舊版瀏覽器,使用 Babel 等工具進行轉譯。 混合環境: 可以使用工具如 Webpack 或 Rollup 來打包模組,這樣可以混合使用 ES 模組和 CommonJS。 總結 ES 模組是未來的標準,具有很多優勢如靜態分析和 Tree Shaking,建議在可能的情況下使用。但根據具體環境和需求,CommonJS 仍然是有效且可靠的選擇。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up