[英]Import es module file from CommonJS TypeScript
I'm trying to import a package where its package.json
specifies "type": "module"
.我正在尝试导入 package,其中
package.json
指定"type": "module"
。 I saw Can Typescript import CommonJS Modules?我看到Typescript 可以导入 CommonJS 模块吗? , but its solution (
--allowJs
) does not work for me. ,但它的解决方案 (
--allowJs
) 对我不起作用。
I've tried setting various values in my tsconfig.json
for module
, moduleResolution
, allow allowJs
.我尝试在
tsconfig.json
中为module
、 moduleResolution
、 allow allowJs
设置各种值。 Both esModuleInteropt
and allowSyntheticDefaultImports
are set to true
. esModuleInteropt
和allowSyntheticDefaultImports
都设置为true
。
I've tried using import... from
, import(...).then()
, import... = require(...)
, and renaming my index.js
and the package's index.js
to index.cjs
.我试过使用
import... from
、 import(...).then()
、 import... = require(...)
,并将我的index.js
和包的index.js
重命名为index.cjs
. They all result in the same error when I run in 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.
I tried removing "type": "module"
from the packages's package.json
, but it relies on other packages with "type": "module"
.我尝试从包的
package.json
中删除"type": "module"
,但它依赖于其他带有"type": "module"
的包。
The last time I tried to figure this out, I gave up and went with a different package. This really doesn't seem like it should be hard to do.上次我试图解决这个问题时,我放弃了,换了一个 package。这看起来确实不难做到。
I found what I'd consider a workaround.我找到了我认为是解决方法的方法。 If I set
"module": "ESNext"
in tsconfig.json
and rename the output to index.mjs
, it works.如果我在 tsconfig.json 中设置
"module": "ESNext"
并将tsconfig.json
重命名为index.mjs
,它就可以工作。 It's not particularly elegant, though.不过,它并不是特别优雅。 There just must be a better way.
必须有更好的方法。
I'd be happy to accept a different, better answer.我很乐意接受一个不同的、更好的答案。
As pointed out in the comment, setting "type": "module"
in my project's package.json
makes it so I do not need to rename index.js
to index.mjs
.正如评论中指出的那样,在我的项目
package.json
中设置"type": "module"
就可以了,所以我不需要将index.js
重命名为index.mjs
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.