javascript - 标准化 TS 和 Babel 之间的默认导入的正确方法是什么?

标签 javascript typescript babeljs

TypeScript 编译器和 Babel 处理默认导出的方式有点不同。 例如:

import Button from 'grommet/components/Button'
console.log(Button)

这将记录 undefined如果通过tsc编译,但它与 Babel 一起按预期工作。但是,如果我们这样做:

import * as Button from 'grommet/components/Button'
console.log(Button)

这表示Button { ... }在 TS 和 { default: Button { ... } }在巴别塔。

可以通过升起标志 esModuleInterop 来修复此差异在编译器选项中。

顺便说一句,没有 esModuleInterop 的其他方法是先用 tsc 进行编译然后是 Babel,但速度很慢,而且我们失去了热插拔功能。我们还可以在运行时修复它,例如 Imported = _Imported.default || _Imported ,但这很容易出错并且增加维护负担。

问题是,是esModuleInterop正确的解决方案是什么?如果是这样, "esModuleInterop": false 是否有任何用例?

最佳答案

The question is, is esModuleInterop the right solution for this

是的。这正是它的设计目的。

If so, is there any use case for "esModuleInterop": false?

esModuleInterop: true 生成更多 JavaScript,让魔法发挥作用就像 babel 一样。如果您希望不进行默认导出(如 babel)的神奇映射而获得轻微的性能提升,请不要使用该标志。

关于javascript - 标准化 TS 和 Babel 之间的默认导入的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52268335/

相关文章:

typescript - 如何从对象数组中提取值

javascript - Babel编译JS导入相对路径失败

带有 babel eslint 解析的 typescript 类型转换

javascript - 编写 promise 以使用传递两个参数的回调

javascript - 隐藏 SVG 元素需要很多时间

css - 在 ionic 中实现半星

javascript - 增加unix时间

javascript - 使用 Typescript 通过 useRef react native 文本输入焦点

javascript - MongoDB/Express/Node 文件上传错误

javascript - 无法通过 AngularJs 加载 Google map