如何让 Typescript 编译 CommonJS 导入?

发布于 2025-01-10 18:25:33 字数 604 浏览 6 评论 0原文

我编写了一个 TS 文件,该文件加载到第 3 方包中,使用 import XXX { YYY, ABC, 123 }from 'XXX';

它将编译为 CommonJS 没有问题,那就可以了。但我想将其编译为 ESModule。我在 TS 配置文件中将 targetmodule 设置更改为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

野却迷人 2025-01-17 18:25:33

对于 module 设置,您可能需要尝试使用 nodenext 而不是 esnext。目前这是实验性的,但它似乎可以通过 CommonJS interop 满足您的需求

我自己没有尝试过,所以我不能保证它会起作用。

You may want to try nodenext instead of esnext for the module 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文