Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Importing from libraries written in ES5 vs. ES6

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?

like image 801
echen Avatar asked Feb 08 '23 03:02

echen


1 Answers

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

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

In 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.

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

//tsconfig.json
module: "commonjs"

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

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

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';

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';

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

Please Provide Corrections to this Answer as Needed

like image 171
echen Avatar answered Mar 28 '23 03:03

echen