为什么我的 TS 代码没有被解释为 CommonJS?
Why is my TS code not interpreted as CommonJS?
我使用了一个被转译为 ES6 的 dependency。
我想在自己的代码中使用 ES2019 特性。
终于要发布ES6了
我的尝试tsconfig
{
"compilerOptions": {
"module": "CommonJS",
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"lib": [
"es2019",
"dom"
],
"target":"ES6"
}
}
这可以编译,但是在浏览器中加载时,我得到 Uncaught ReferenceError: exports is not defined
是由我的一个文件引起的。试图解决我将 "@babel/plugin-transform-modules-commonjs"
添加到 .babelrc:
{
"plugins": [
"@babel/plugin-transform-modules-commonjs"
]
}
这解决了问题,但我不明白为什么需要它。我的 tsconfig 已经将模块声明为 commonjs,并且依赖项也在其 tsconfig(!?) 中指定使用 commonjs。
CommonJS
模块设置主要用于Node应用,因为Node使用commonjs模块系统。默认情况下浏览器不理解 commonjs 模块,所以这就是你得到 exports is not defined
错误的原因。
据我了解,你想输出ES6模块,所以你应该使用"module": "ES6"
我使用了一个被转译为 ES6 的 dependency。
我想在自己的代码中使用 ES2019 特性。
终于要发布ES6了
我的尝试tsconfig
{
"compilerOptions": {
"module": "CommonJS",
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"lib": [
"es2019",
"dom"
],
"target":"ES6"
}
}
这可以编译,但是在浏览器中加载时,我得到 Uncaught ReferenceError: exports is not defined
是由我的一个文件引起的。试图解决我将 "@babel/plugin-transform-modules-commonjs"
添加到 .babelrc:
{
"plugins": [
"@babel/plugin-transform-modules-commonjs"
]
}
这解决了问题,但我不明白为什么需要它。我的 tsconfig 已经将模块声明为 commonjs,并且依赖项也在其 tsconfig(!?) 中指定使用 commonjs。
CommonJS
模块设置主要用于Node应用,因为Node使用commonjs模块系统。默认情况下浏览器不理解 commonjs 模块,所以这就是你得到 exports is not defined
错误的原因。
据我了解,你想输出ES6模块,所以你应该使用"module": "ES6"