You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 06:55:28