如何将TypeScript默认导出编译为module.exports匿名函数?
解决TypeScript编译导出格式问题
要让你的TypeScript默认导出编译为module.exports = ...,可以按以下两种方式处理:
方式1:修改代码(仅TypeScript编译器即可实现)
将export default替换为TypeScript的export =语法,适配CommonJS的导出规则:
const greet = (name: string): string => { return 'Hi ' + name; }; export = greet;
编译后会生成你期望的结果:
module.exports = function (name) { return 'Hi ' + name; };
方式2:理解TypeScript的导出映射规则
TypeScript对ES模块和CommonJS模块的导出有固定映射逻辑:
- ES模块的
export default会被编译为CommonJS的exports.default - CommonJS的
module.exports对应TypeScript的export =语法
因此,仅靠调整TypeScript编译器配置,无法将export default直接转为module.exports——这是TypeScript为保持ES模块与CommonJS模块兼容性的设计规则。
另外,你当前编译结果中箭头函数被转为普通function,是因为配置了target: "ES5"(ES5不支持箭头函数),属于预期行为。若想保留箭头函数,可将target改为"ES6"或更高版本。
内容的提问来源于stack exchange,提问作者rodolfo_r
相关产品推荐
相关产品推荐

