TypeScript从ES5编写的库与ES6进行导入 [英] TypeScript Importing from libraries written in ES5 vs. ES6

查看:844
本文介绍了TypeScript从ES5编写的库与ES6进行导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行

如果未捕获TypeError: es5_lib_1.default不是一个函数

有什么问题?

推荐答案

ES6模块规格与CommonJ有所不同,描述这里。这引入了一些兼容性问题,这些问题在TypeScript中有些令人激动。

The ES6 module spec differ slightly from CommonJs, described Here. This introduces some compatibility issues that are somewhat exasperated in TypeScript.

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

TypeScript tries to guess the correct way to transpile import/require statements based on two inputs


  • tsconfig.json 中的模块

  • export 语句如何写在相应的 .d.ts 文件

  • The module property in tsconfig.json
  • How the export statement is written in the corresponding .d.ts file

tsconfig.json 文件中,我们可以设置模块格式transp iled输出将会使用。例如, module:'es6'

In the tsconfig.json file, we can set module format the transpiled output will use. For example, module: 'es6'

我们在这里选择的内容对导入语法TypeScript有何影响会允许。这也受到如何写入相应的 .d.ts 形状文件的影响。

What we choose here have an impact on the kind of importing syntax TypeScript will allow. Which also impacted by how the corresponding .d.ts shape files are written.

//tsconfig.json
module: "commonjs"

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

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



如果我们是从导入一个CommonJS库和我们的输出模块定位ES6我们必须使用:



If we are Importing From a CommonJS library and Our Output module targets ES6, we must use:

//tsconfig.json
module: "es6"

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

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



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



If we are importing From a ES6 library, we can use the import {default ... } style regardless of the targeted Output module format

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

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

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



这对 .d.ts 我们从 tsd install 中检索的文件?



根据我们所针对的输出,我们可能需要更改 .d.ts 文件安装完成以满足我们的需求。大多数 .d.ts 文件是为 commonjs 模块编写的,因此将使用 export = < lib> 风格。但是如果要定位ES6输出,您将需要编辑它,并将其更改为 export default

What does this mean for .d.ts files we retrieve from tsd install?

Depending on which output we are targeting, we may have to alter the .d.ts files after they've been installed to suit our needs. Most .d.ts files are written for commonjs modules and thus will use the export = <lib> style. But if you want to target ES6 output, you will need to edit this like and change it to export default

这篇关于TypeScript从ES5编写的库与ES6进行导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆