我正在尝试导入一个包,其中它的 package.json
指定 "type": "module"
。我看到了Can Typescript import CommonJS Modules? , 但它的解决方案 (--allowJs
) 对我不起作用。
我尝试在我的 tsconfig.json
中为 module
、moduleResolution
、allow allowJs
设置各种值. esModuleInteropt
和 allowSyntheticDefaultImports
都设置为 true
。
我试过使用 import ... from
、import(...).then()
、import ... = require(. ..)
,并将我的 index.js
和包的 index.js
重命名为 index.cjs
。当我在 Node 中运行时,它们都会导致相同的错误:
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 "
.
上次我试图解决这个问题时,我放弃了,选择了另一个包。这看起来真的不应该很难做到。
最佳答案
我找到了我认为的解决方法。如果我在 tsconfig.json
中设置 "module": "ESNext"
并将输出重命名为 index.mjs
,它就可以工作。不过,它并不是特别优雅。只是必须有更好的方法。
我很乐意接受一个不同的、更好的答案。
正如评论中指出的那样,在我项目的 package.json
中设置 "type": "module"
就可以了,所以我不需要重命名 index.js
到 index.mjs
。
关于javascript - 从 CommonJS TypeScript 导入 es 模块文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69365351/