如何配置TypeScript将ES6模块转译为Node.js的CommonJS格式?
解决方案
要让TypeScript把ES6模块语法转成Node.js的CommonJS导出格式,同时保留const等ES6语法特性,只需在tsconfig.json的compilerOptions中添加"module": "CommonJS"配置项即可。
原因说明
target选项控制输出JavaScript的语法版本(比如是否保留const、箭头函数、let等ES6+特性),你设置为"ES6"是正确的,能保留这些特性。module选项控制输出的模块系统规范,当未显式设置时,若target为ES6或更高版本,TypeScript默认会使用ES6作为模块系统,因此输出的还是ES模块的export default语法。
修改后的tsconfig.json
{ "compilerOptions": { "incremental": true, "target": "ES6", "module": "CommonJS", // 新增该行配置 "moduleResolution": "Node", "esModuleInterop": true, "declaration": true, "declarationMap": true, "removeComments": true, "forceConsistentCasingInFileNames": true, "strict": true, "sourceRoot": "", "outDir": "dist" }, "include": [ "./src/main.ts" ], "exclude": [] }
修改后重新执行tsc编译,输出的JS文件会将export default xyz转为module.exports = xyz,同时保留const等ES6语法特性。
内容的提问来源于stack exchange,提问作者sjiamnocna
相关产品推荐
相关产品推荐

