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

解决Rollup TypeScript插件生成嵌套声明目录与冗余.d.ts文件问题

解决Rollup构建后类型文件输出不符合预期的问题

问题现状

当前构建后dist目录生成了index.js、rollup.config.d.ts,且index.d.ts嵌套在src子目录下,但期望dist目录仅存在index.js和根目录下的index.d.ts;同时若移除tsconfig中对rollup.config.ts的include配置,会触发Rollup语法错误。

解决方案

1. 拆分TS配置文件

为Rollup配置文件单独创建一个小型TS配置(比如命名为tsconfig.config.json),仅用于处理rollup.config.ts,避免主TS配置生成多余的类型文件:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "NodeNext",
    "target": "ES2020",
    "allowSyntheticDefaultImports": true
  },
  "include": ["rollup.config.ts"]
}

主tsconfig.json仅处理src目录下的业务代码:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "NodeNext",
    "declaration": true,
    "outDir": "dist",
    "strict": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

2. 修改构建脚本,指定配置文件的TS配置

更新构建命令,让@rollup/plugin-typescript处理Rollup配置文件时使用单独的TS配置:

rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript=tsconfig:tsconfig.config.json

3. 配置Rollup插件,指定类型文件输出路径

在rollup.config.ts中,给@rollup/plugin-typescript配置指定类型文件输出目录,并排除配置文件本身:

import typescript from '@rollup/plugin-typescript';

export default {
  input: 'src/index.ts',
  output: {
    file: 'dist/index.js',
    format: 'esm' // 根据需求调整输出格式
  },
  plugins: [
    typescript({
      tsconfig: './tsconfig.json',
      declaration: true,
      declarationDir: 'dist',
      exclude: ['rollup.config.ts']
    })
  ]
};

效果验证

执行构建命令后,dist目录将仅生成index.js和根目录下的index.d.ts,同时Rollup配置文件的语法不会出现错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:07:45