如何禁用rollup-plugin-dts的导出自动合并功能?
解决方案
方案1:用tsc生成声明后重命名(最简单可靠)
既然tsc直接编译生成的lib/server.d.ts格式完全符合要求,仅文件名不符合需求,可跳过rollup-plugin-dts,通过脚本重命名文件:
- 在
package.json的scripts中添加命令:
"scripts": { "build:declaration": "tsc --emitDeclarationOnly && cp lib/server.d.ts server/index.d.ts" }
Windows环境将cp替换为copy即可。
2. 执行npm run build:declaration,就能得到格式完全匹配源码导出结构的server/index.d.ts。
方案2:配置rollup-plugin-dts禁用导出合并
若坚持使用rollup-plugin-dts,可通过插件参数禁用导出合并优化,修改rollup配置文件:
import dts from 'rollup-plugin-dts'; export default [ // 其他打包配置... { input: './src/server.ts', output: { file: './server/index.d.ts', format: 'es' }, plugins: [ dts({ preserve: true, // 保留原导出结构,禁用自动合并 respectExternal: true // 确保外部导出逻辑不被修改 }) ] } ];
若preserve选项不生效,可尝试添加transpileOnly: true跳过插件的额外转换逻辑:
dts({ transpileOnly: true })
方案3:调整tsconfig直接生成目标目录的声明文件
修改tsconfig.json,让tsc直接将声明文件输出到目标目录,再重命名:
- 在
compilerOptions中设置declarationDir: "./server" - 添加
include: ["./src/server.ts"] - 执行
tsc --emitDeclarationOnly后,server目录会生成server.d.ts,再通过脚本重命名为index.d.ts即可。
关键原因说明
rollup-plugin-dts默认会对导出语句做优化合并,包括将多条独立export合并为一条,并给类型导出添加type前缀(TS 3.8+语法),这种写法不兼容旧版TypeScript。而tsc默认不会做这类优化,完全按照源码的导出结构生成声明文件,因此直接使用tsc的产物更适配旧版项目需求。
内容的提问来源于stack exchange,提问作者Aero Wang
相关产品推荐
相关产品推荐

