【问题标题】:TypeScript Importing from libraries written in ES5 vs. ES6从 ES5 与 ES6 编写的库中导入 TypeScript
【发布时间】:2016-04-09 22:07:38
【问题描述】:

运行依赖于外部库的 转译 TypeScript 代码时出现奇怪的错误

Uncaught TypeError: es5_lib_1.default is not a function

怎么了?

【问题讨论】:

标签: typescript ecmascript-6 commonjs


【解决方案1】:

ES6 模块规范与 CommonJs 略有不同,描述为Here。这引入了一些在 TypeScript 中有些激怒的兼容性问题。

TypeScript 尝试根据两个输入猜测转换 import/require 语句的正确方法

  • tsconfig.json 中的 module 属性
  • export 语句如何写入对应的.d.ts 文件中

tsconfig.json 文件中,我们可以设置转译输出将使用的模块格式。比如module: 'es6'

我们在此处选择的内容会影响 TypeScript 允许的导入语法类型。这也受到相应.d.ts 形状文件的编写方式的影响。

如果我们从一个CommonJS库导入并且我们的输出模块以CommonJS为目标,我们必须使用

//tsconfig.json
module: "commonjs"

//.d.ts
declare module 'foo' {
    exports = Foo;
}

// App.ts
import Foo = require('foo');

如果我们导入一个 CommonJS 库并且我们的输出模块针对 ES6,我们必须使用:

//tsconfig.json
module: "es6"

//.d.ts
declare module 'foo' {
    exports default Foo;
}

// App.ts
import {default as Foo} from 'foo';

如果我们从 ES6 库中导入 ,我们可以使用 import {default ... } 样式,而不管目标输出模块格式如何

//tsconfig.json
module: "es6|commonjs"

//.d.ts
declare module 'foo.es6' {
    exports default FooES6;
}

// App.ts
import {default as FooES6} from 'foo.es6';

这对于我们从tsd install 检索到的.d.ts 文件意味着什么?

根据我们的目标输出,我们可能需要在安装 .d.ts 文件以满足我们的需要后对其进行更改。大多数.d.ts 文件是为commonjs 模块编写的,因此将使用export = <lib> 样式。但是如果你想以 ES6 输出为目标,你需要编辑它并将其更改为 export default

请根据需要提供对此答案的更正

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 2020-03-21
    • 1970-01-01
    • 2016-11-20
    • 2016-07-25
    相关资源
    最近更新 更多