【问题标题】:TypeScript and JS module import misunderstandingTypeScript 和 JS 模块导入误区
【发布时间】:2019-05-09 04:10:33
【问题描述】:

我以为我了解导入的工作原理,但今天发现我没有。

拥有纯 javascript 模块,例如:

function MyClass() { ... }

util.inherits(MyClass, EventEmitter);

MyClass.prototype.someMethod = funtion(x) { ... }

...

module.exports = MyClass;

现在我在 TypeScript 文件中导入这个模块(因为我认为它使用与 ES6 导入相同的语法)并发现它有效:

import * as MyWebSocket from '../utils/websocket';

而这 - 不会:

import MyWebSocket from '../utils/websocket';

这也不起作用:

import { MyWebSocket } from '../utils/websocket';

据我了解,import X from Y 应该可以工作,如果模块导出带有 default 关键字的东西,例如 export default X(并且相等的 ES5 语法是 module.exports = X)。如果导出非默认内容,import { X } from Y 应该可以工作(类似 ES5 语法是 module.exports = { X })。

但我知道我错了。你能帮我修一下吗?

【问题讨论】:

  • 你在 tsconfig 中尝试过 "esModuleInterop": true 吗?
  • @Praveen 尝试过,但它使代码的其他遗留部分损坏。例如 Bluebird 被设置为 global.Promise = Bluebird 并且这被破坏了。在设置该标志后,应用程序的许多其他部分也无法编译。

标签: typescript ecmascript-6 node-modules ecmascript-5


【解决方案1】:

module.exports = something 不是 ES5 语法,实际上 ES5 规范中没有“模块”。这个模块系统叫做CommonJS,被Node.JS采用。

要使 module.exports = X 中的 import X from Y 在 TypeScript 中工作,您应该启用 esModuleInterop: true,否则,您必须使用 import * as X from Y

【讨论】:

    猜你喜欢
    • 2015-05-08
    • 2015-07-19
    • 2017-05-04
    • 1970-01-01
    • 2018-12-29
    • 2019-02-05
    • 2020-06-01
    • 2021-05-03
    • 1970-01-01
    相关资源
    最近更新 更多