Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: esnext compiler option destroys es6 import from external lib

When setting ether the module or target property of the compiler options to esnext (id like to use import("example") statements), es6 import statements stop working for npm installed librarys (local modules sill work: e.g. "./test.ts").

So this import * as asd from "testmodule"; throws cannot find module 'testmodule'. However omitting both properies makes it work. Why is this and what es standard should I use to keep import("example") and import * as asd from "testmodule"; statements?


Here is my full tsconfig.json:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "esnext",
    "target": "esnext",
    "allowJs": true,
    "sourceMap": true
  }
}

like image 822
MaximilianMairinger Avatar asked Aug 06 '19 19:08

MaximilianMairinger


1 Answers

TLDR: When "module" is anything aside from "commonjs" you need to explicitly specifiy a "moduleResolution" value of "node" for this to work. Setting "commonjs"for"module" does so implicitly.

As this is by no means obvious, I strongly encourage explicitly specifying "moduleResolution" whenever specifying "module".

I strongly recommend that you always specify the output module format explicitly.

Additionally, despite the names of certain options, "target" and "module" are independent and orthogonal. They mean very different things and must not be confused.

{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "esnext",
    "moduleResolution": "node",
    "target": "esnext", // this isn't relevant
    "allowJs": true,
    "sourceMap": true
  }
}

"commonjs" is an output module format. ESNext import(...) statements are a transpiled into the output module format just like other module syntax such as ES2015 import and export statements.

When you specify --module esnext, you are telling TypeScript not to transpile any module syntax at all. That's the point of --module it specifies the output module format, not the source module format.

like image 52
Aluan Haddad Avatar answered Nov 10 '22 01:11

Aluan Haddad