【问题标题】:Import es module file from CommonJS TypeScript从 CommonJS TypeScript 导入 es 模块文件
【发布时间】:2021-11-20 17:01:38
【问题描述】:

我正在尝试导入其package.json 指定"type": "module" 的包。我看到了Can Typescript import CommonJS Modules?,但它的解决方案 (--allowJs) 对我不起作用。

我尝试在我的tsconfig.json 中为modulemoduleResolution、允许allowJs 设置各种值。 esModuleInteroptallowSyntheticDefaultImports 都设置为 true

我尝试使用import ... fromimport(...).then()import ... = require(...),并将我的index.js 和包的index.js 重命名为index.cjs。当我在节点中运行时,它们都会导致相同的错误:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: E:\src\...\node_modules\stringify-object\index.js
require() of ES modules is not supported.
require() of E:\src\...\node_modules\stringify-object\index.js from E:\src\...\index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename E:\src\...\node_modules\stringify-object\index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from E:\src\...\node_modules\stringify-object\package.json.

我尝试从包的package.json 中删除"type": "module",但它依赖于带有"type": "module" 的其他包。

上次我试图解决这个问题时,我放弃了,选择了一个不同的包。这看起来真的不难做到。

【问题讨论】:

  • “这似乎并不难做到。” 是的,我们现在正处于从旧方式转移到旧方式的不舒服的地方新的方法。最终它会再次变得简单,但是... 新方法必须有所不同是有充分理由的,但它仍然很痛苦。对包作者来说是两倍甚至三倍。

标签: javascript node.js typescript commonjs


【解决方案1】:

我找到了我认为的解决方法。如果我在tsconfig.json 中设置"module": "ESNext" 并将输出重命名为index.mjs,它可以工作。不过,它并不是特别优雅。只是必须有更好的方法。

我很乐意接受不同的、更好的答案。


正如评论中指出的那样,在我的项目的 package.json 中设置 "type": "module" 就可以了,所以我不需要将 index.js 重命名为 index.mjs

【讨论】:

  • 如果您将"type": "module" 放在您的package.json 中,则不必使用.mjs 扩展名。您在上面所做的是告诉 TypeScript 使用 ESM(本机 JavaScript 模块)而不是 CommonJS。因此,如果您通过 package.json 告诉 Node.js 这就是您正在做的事情,则无需使用文件名来告诉它。
  • 啊,我在设置 module: esnext 之前确实尝试过,所以也许可以这样做。
  • 这对我不起作用..任何建议
  • @Ahsan 你在 package.json 中设置了"type": "module",在 tsconfig.json 中设置了"module": "ESNext"
  • @dx_over_dt...是的,也试过了
猜你喜欢
  • 1970-01-01
  • 2016-07-30
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 2021-04-07
  • 2021-10-30
相关资源
最近更新 更多