打字稿:esnext 编译器选项会破坏来自外部库的 es6 导入
当将编译器选项的 module
或 target
属性设置为 esnext(id 喜欢使用 import("example")
语句时)),es6 导入语句停止为 npm install
ed 库工作(本地模块仍然有效:例如 "./test.ts"
).
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"
).
所以这个 import * asd from "testmodule";
抛出 cannot find module 'testmodule'
.然而,省略这两个属性使它工作.为什么是这样,我应该使用什么标准来保持 import("example")
和 import * asd from "testmodule";
语句?
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?
这是我的完整 tsconfig.json:
Here is my full tsconfig.json:
{
"compilerOptions": {
"outDir": "./dist/",
"module": "esnext",
"target": "esnext",
"allowJs": true,
"sourceMap": true
}
}
当 "module"
是 "commonjs"
之外的任何东西时,你需要指定一个 moduleResolution"
node"
的值.指定 "commonjs"
会隐式设置它.
When "module"
is anything aside from "commonjs"
you need to specifiy a "moduleResolution"
value of "node"
. Specifying "commonjs"
sets this implicitly.
我强烈建议您始终明确指定输出模块格式.
I strongly recommend that you always specify the output module format explicitly.
此外,尽管某些选项的名称不同,target"
和 module"
是独立且正交的.它们的含义非常不同,不能混淆.
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"
是一种输出模块格式.ESNext import(...)
语句被转译为输出模块格式,就像其他模块语法如 ES2015 import
和 export
语句一样.
"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.
当您指定 --module esnext
时,您是在告诉 TypeScript 根本不要转译任何模块语法.这就是 --module
的重点,它指定输出模块格式,而不是源模块格式.
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.