5

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

4

1 回答 1

4

文档

为了更好地与 JS 生态系统中的现有用法兼容,Node.js 除了[默认导入]尝试确定每个导入的 CommonJS 模块的 CommonJS 命名导出,以使用静态分析过程将它们作为单独的 ES 模块导出提供。

[…]

命名导出的检测基于常见的语法模式,但并不总是正确检测命名导出。在这些情况下,使用上述默认导入表单可能是更好的选择。

命名导出检测涵盖了许多常见的导出模式、重新导出模式以及构建工具和转译器输出。参见cjs-module-lexer 实现的确切语义。

于 2020-12-30T18:21:34.943 回答