簡體   English   中英

ES 模塊何時可以導入名為 export 的 CommonJS?

[英]When can a CommonJS named export be imported by an ES module?

我有一個 ES 模塊,它使用我創作的 CommonJS 模塊的命名導出。

es.mjs

import { MyNamedExport } from './commonjs.cjs';

console.log(MyNamedExport);

commonjs.cjs (好一個)

exports.MyNamedExport = 'OK';

當我像這樣在 Node.js 中運行 ES 模塊時,一切都很好。

> node ./es.mjs
OK

無論如何,如果 CommonJS 模塊中的導出部分以某種看似無關的方式進行了更改,即通過添加一對括號,命名導出將停止工作。

commonjs.cjs (壞的一個)

(exports).MyNamedExport = 'OK';
> node ./es.mjs
file:///path/to/current/folder/es.mjs:1
import { MyNamedExport } from './commonjs.cjs';
         ^^^^^^^^^^^^^
SyntaxError: Named export 'MyNamedExport' not found. The requested module './commonjs.cjs' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from './commonjs.cjs';
const { MyNamedExport } = pkg;

    at ModuleJob._instantiate (node:internal/modules/esm/module_job:104:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:149:5)
    at async Loader.import (node:internal/modules/esm/loader:166:24)
    at async Object.loadESM (node:internal/process/esm_loader:68:5)

當然,當我的 CommonJS 命名導出被另一個 CommonJS 模塊導入時,括號沒有任何區別。

為什么會這樣?

當我寫一個 CommonJS 模塊來確保命名的導出可以被 ES 模塊導入時,我應該怎么做?

文檔

為了更好地兼容 JS 生態系統中的現有用法,Node.js 除了[默認導入]嘗試確定每個導入的 CommonJS 模塊的 CommonJS 命名導出,以使用 static 分析過程將它們作為單獨的 ES 模塊導出提供。

[…]

命名導出的檢測基於常見的語法模式,但並不總是正確檢測命名導出。 在這些情況下,使用上述默認導入表單可能是更好的選擇。

命名導出檢測涵蓋了許多常見的導出模式、重新導出模式以及構建工具和轉譯器輸出。 有關實現的確切語義,請參見cjs-module-lexer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM