我有一个 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 模块导入时,我应该怎么做?