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

如何用TypeScript编译选项覆盖package.json的`type`配置实现双发布?

在TypeScript node16模块模式下实现ESM+CJS双发布

当使用--module node16 --moduleResolution node16时,TypeScript会严格遵循Node.js的模块规范,包括强制文件扩展名、支持条件导出等特性,但默认只能输出单一模块格式(ESM或CJS)。目前TypeScript没有直接的编译选项可以覆盖package.json的type配置或强制修改输出文件扩展名,但可以通过双tsconfig配置方案实现双发布,同时保留node16模式的所有核心特性。

具体实现步骤

1. 创建两个tsconfig配置文件

分别针对ESM和CJS编译,复用基础配置的同时指定不同的输出目录和扩展名规则:

tsconfig.esm.json(ESM编译配置)

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "node16",
    "moduleResolution": "node16",
    "outDir": "./dist/esm",
    "target": "ES2022",
    "declaration": true,
    "declarationDir": "./dist/types",
    "moduleSuffixes": [".mjs"]
  },
  "include": ["src/**/*"]
}

tsconfig.cjs.json(CJS编译配置)

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "node16",
    "moduleResolution": "node16",
    "outDir": "./dist/cjs",
    "target": "ES2022",
    "declaration": true,
    "declarationDir": "./dist/types",
    "moduleSuffixes": [".js"]
  },
  "include": ["src/**/*"]
}
  • moduleSuffixes:指定输出文件的扩展名后缀,TypeScript会自动为编译后的文件添加对应的扩展名,无需手动修改。
  • declarationDir:将类型声明文件统一输出到dist/types目录,避免重复生成。

2. 配置package.json的脚本与条件导出

添加编译命令,并通过条件导出指定ESM和CJS的入口:

package.json核心配置

{
  "type": "module",
  "scripts": {
    "build:esm": "tsc -p tsconfig.esm.json",
    "build:cjs": "tsc -p tsconfig.cjs.json",
    "build": "npm run build:esm && npm run build:cjs"
  },
  "exports": {
    ".": {
      "import": "./dist/esm/index.mjs",
      "require": "./dist/cjs/index.js",
      "types": "./dist/types/index.d.ts"
    }
  },
  "main": "./dist/cjs/index.js",
  "module": "./dist/esm/index.mjs",
  "types": "./dist/types/index.d.ts"
}
  • type: module:设置默认模块格式为ESM,不影响CJS的条件导出逻辑。
  • exports:通过条件导出,让Node.js根据import或require自动选择对应的入口文件。

3. 注意事项

  • 源码中的所有导入必须使用完整文件扩展名(比如import utils from './utils.ts'),这是node16模式的强制要求,编译后会自动替换为对应的.mjs或.js扩展名。
  • 若需导入JSON文件,需开启resolveJsonModule: true,且导入时必须加上.json扩展名。
  • 避免在源码中混用ESM和CJS语法(如同时使用import和require),node16模式会严格检查模块一致性。

总结

这种方案无需手动修改文件扩展名或package.json的type配置,既能完全保留node16模式的所有特性(node import、子路径导出、条件导出、强制扩展名规则),又能实现ESM和CJS的双发布,满足不同场景的模块使用需求。

内容的提问来源于stack exchange,提问作者everett1992

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:17:37