运行时出现奇怪的错误转译的依赖于外部库的 TypeScript 代码
Such as Uncaught TypeError: es5_lib_1.default is not a function
怎么了?
ES6 模块规范与 CommonJs 略有不同,描述Here http://www.jbrantly.com/es6-modules-with-typescript-and-webpack/#importinglibraries。这引入了一些兼容性问题,这些问题在 TypeScript 中有些加剧。
TypeScript 尝试猜测正确的转译方式import/require
基于两个输入的语句
- The
module
财产在tsconfig.json
- How the
export
语句写在相应的.d.ts
file
In the 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';
这意味着什么.d.ts
我们从中检索的文件tsd install
?
根据我们的目标输出,我们可能需要改变.d.ts
安装后的文件以满足我们的需要。最多.d.ts
文件是为commonjs
模块,因此将使用export = <lib>
风格。但是如果你想以 ES6 输出为目标,你需要像这样编辑并将其更改为export default
请根据需要对此答案进行更正
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)