TypeScript Import from libraries written in ES5 and ES6

I get weird errors when running transpiled TypeScript code, which depends on external libraries

For example, Uncaught TypeError: es5_lib_1.default is not a function

What's wrong?

+2
source share
1 answer

The specification of the ES6 module is slightly different from the CommonJs described here . This leads to some compatibility issues that are somewhat annoying in TypeScript.

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

  • 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 the format of the module that the transmitted output will be used. For example, module: 'es6'

What we select here affects the type of import syntax of TypeScript. Which also influenced how the corresponding .d.ts form files are .d.ts .

If we import from the CommonJS library, and our Output module targets CommonJS, we should use

 //tsconfig.json module: "commonjs" //.d.ts declare module 'foo' { exports = Foo; } // App.ts import Foo = require('foo'); 

If we import from the CommonJS library and our Output module targets ES6, we should use:

 //tsconfig.json module: "es6" //.d.ts declare module 'foo' { exports default Foo; } // App.ts import {default as Foo} from 'foo'; 

If we import from the ES6 library, we can use the import {default ... } style regardless of the target format of the output module

 //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 that we extract from tsd install ?

Depending on what kind of result we are aiming for, we may have to modify the .d.ts files after installing them according to our needs. Most .d.ts files .d.ts written for commonjs modules and thus will use the export = <lib> style. But if you want to customize the output of ES6, you will need to edit this as well and change it to export default

Please provide corrections for this answer as necessary.

+5
source

Source: https://habr.com/ru/post/1243007/


All Articles