I get weird errors when running transpiled TypeScript code that depends on external libraries
Such as Uncaught TypeError: es5_lib_1.default is not a function
What's wrong?
The ES6 module spec differ slightly from CommonJs, described Here. This introduces some compatibility issues that are somewhat exasperated in TypeScript.
TypeScript tries to guess the correct way to transpile import/require
statements based on two inputs
module
property in tsconfig.json
export
statement is written in the corresponding .d.ts
fileIn the tsconfig.json
file, we can set module format the transpiled output will use. For example, module: 'es6'
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');
//tsconfig.json
module: "es6"
//.d.ts
declare module 'foo' {
exports default Foo;
}
// App.ts
import {default as Foo} from 'foo';
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With