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 install
ed 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
}
}
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.
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