为何tsconfig配置CommonJS后TS代码仍报exports未定义?
开发场景与初始配置
- 项目使用了一个
react-diagrams依赖库,该依赖已被转译为ES6版本 - 开发需求:自身编写的代码可以使用ES2019语法特性,最终编译输出ES6兼容版本的产物
- 编写的tsconfig配置如下:
{ "compilerOptions": { "module": "CommonJS", "removeComments": true, "preserveConstEnums": true, "sourceMap": true, "lib": [ "es2019", "dom" ], "target": "ES6" } }
报错现象与待解疑问
- 上述tsconfig配置可正常完成TypeScript编译,但在浏览器加载运行产物时,其中一个业务文件抛出报错:
Uncaught ReferenceError: exports is not defined - 为解决该报错,在项目
.babelrc中新增了@babel/plugin-transform-modules-commonjs插件,配置如下:
{ "plugins": [ "@babel/plugin-transform-modules-commonjs" ] }
- 新增插件后报错问题得到解决,但始终无法理解背后的原因:tsconfig已经明确声明模块格式为CommonJS,且引用的依赖库自身的tsconfig也指定使用CommonJS模块格式,为什么还需要额外通过Babel做模块格式转换?
内容的提问来源于stack exchange,提问作者ajthinking
相关产品推荐
相关产品推荐

