ECMAScript 模組

ECMAScript 模組 (ESM) 是 規範,用於在 Web 中使用模組。它受到所有現代瀏覽器支援,並且是為 Web 編寫模組化程式碼的建議方式。

Webpack 支援處理 ECMAScript 模組以最佳化它們。

匯出

export 關鍵字允許將 ESM 中的東西公開給其他模組

export const CONSTANT = 42;

export let variable = 42;
// only reading is exposed
// it's not possible to modify the variable from outside

export function fun() {
  console.log('fun');
}

export class C extends Super {
  method() {
    console.log('method');
  }
}

let a, b, other;
export { a, b, other as c };

export default 1 + 2 + 3 + more();

匯入

import 關鍵字允許從其他模組取得 ESM 中的東西的參考

import { CONSTANT, variable } from './module.js';
// import "bindings" to exports from another module
// these bindings are live. The values are not copied,
// instead accessing "variable" will get the current value
// in the imported module

import * as module from './module.js';
module.fun();
// import the "namespace object" which contains all exports

import theDefaultValue from './module.js';
// shortcut to import the "default" export

將模組標示為 ESM

預設情況下,webpack 會自動偵測檔案是 ESM 還是其他模組系統。

Node.js 建立一種方式,透過使用 package.json 中的屬性來明確設定檔案的模組類型。在 package.json 中設定 "type": "module" 會強制此 package.json 下的所有檔案都成為 ECMAScript 模組。相反地,設定 "type": "commonjs" 會強制它們成為 CommonJS 模組。

{
  "type": "module"
}

此外,檔案可以使用 .mjs.cjs 副檔名來設定模組類型。.mjs 會強制將它們設為 ESM,.cjs 會強制將它們設為 CommonJs。

在 DataURIs 中使用 text/javascriptapplication/javascript mime 類型也會強制將模組類型設為 ESM。

除了模組格式之外,將模組標記為 ESM 也會影響解析邏輯、互操作邏輯和模組中的可用符號。

ESM 中的匯入會更嚴格地解析。相對要求必須包含檔案名稱和檔案副檔名(例如 *.js*.mjs),除非您已使用 fullySpecified=false 停用此行為。

只能從非 ESM 匯入「預設」匯出。無法使用命名匯出。

無法使用 CommonJs 語法:requiremoduleexports__filename__dirname

1 貢獻者

sokra