如何让 Typescript 编译 CommonJS 导入?
我编写了一个 TS 文件,该文件加载到第 3 方包中,使用 import XXX { YYY, ABC, 123 }from 'XXX';
它将编译为 CommonJS 没有问题,那就可以了。但我想将其编译为 ESModule。我在 TS 配置文件中将 target
和 module
设置更改为 esnext
,它确实可以编译,但是,当我运行该文件时,它错误提示:
SyntaxError: Named export 'ABC' not found. The requested module 'XXX' 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 'XXX';
const { ABC } = pkg;
是否有任何设置可以用来告诉 Typescript 将导入转换为错误消息中显示的导入类型?
I have written a TS file, that loads in a 3rd party package, using import XXX { YYY, ABC, 123 }from 'XXX';
It will compile to CommonJS no issue, and thats OK. But I'd like to compile it to an ESModule. I changed the target
and module
settings to esnext
in my TS config file, and it does compile, however, when I run the file, it errors out saying:
SyntaxError: Named export 'ABC' not found. The requested module 'XXX' 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 'XXX';
const { ABC } = pkg;
Is there any settings I can use to tell Typescript to convert the imports to the import tye shown in the error message?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于
module
设置,您可能需要尝试使用nodenext
而不是esnext
。目前这是实验性的,但它似乎可以通过 CommonJS interop 满足您的需求。我自己没有尝试过,所以我不能保证它会起作用。
You may want to try
nodenext
instead ofesnext
for themodule
setting. This is currently experimental but it seems to address your need with CommonJS interop.I haven't tried it myself so I cannot promise it will work.