You need to enable JavaScript to run this app. @rollup/plugin-typescript实现UMD+ESM双构建及类型声明生成遇报错
优惠活动
大模型
产品
解决方案
定价
更多

@rollup/plugin-typescript实现UMD+ESM双构建及类型声明生成遇报错

切换@rollup/plugin-typescript实现双格式库构建的配置问题

原有可正常运行的配置

此前使用非官方插件rollup-plugin-typescript2时,所有构建流程完全正常,可产出符合预期的UMD、ESM单文件产物及类型声明文件。

原有Rollup构建配置

import typescript from 'rollup-plugin-typescript2'
import pkg from '../package.json'
export default {
  input: 'src/index.ts',
  output: [
    {
      file: pkg.main,
      format: 'umd',
      name: pkg.name,
      sourcemap: true
    },
    {
      file: pkg.module,
      format: 'esm',
      sourcemap: true
    },
  ],
  plugins: [
    typescript({
        tsconfig: "src/tsconfig.json",
        useTsconfigDeclarationDir: true
    }),
  ],
}

关联配置

  • package.json相关配置:
(...)
  "scripts": {
    "build": "rollup -c ./scripts/dist.js",
  },
  "main": "dist/index.js",
  "module": "dist/index.esm.js",
  "files": [
    "dist"
  ],
  (...)
  • tsconfig.json相关配置:
(...)
  "compilerOptions": {
    "rootDir": "./src",
    "outDir": "./dist",
    "declaration": true,
    "declarationDir": "./dist/@types/chrisweb-utilities",
    (...)

原有正常构建的产物目录

/dist
|-@types
 |-index.d.ts
|-index.js
|-index.esm.js
|-index.esm.js.map
|-index.js.map

切换官方插件后的连续报错

为统一项目插件栈,将插件替换为官方维护的@rollup/plugin-typescript(其他仅需单ESM构建的项目使用该插件无异常),调整配置后遇到连环冲突报错:

  1. 首次保留原useTsconfigDeclarationDir配置时,插件抛出不识别专属配置项的错误:(!) Plugin typescript: @rollup/plugin-typescript TS5023: Unknown compiler option 'useTsconfigDeclarationDir'.
  2. 删除该专属配置项后,触发下一层校验报错:[!] (plugin typescript) Error: @rollup/plugin-typescript: 'dir' must be used when 'outDir' is specified.
    按照报错提示给两个output条目都增加dir: "dist"配置后,又触发Rollup核心的规则校验报错:[!] Error: You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.
  3. 尝试删除file配置只保留dir参数,构建不再报错,但两个输出产物因文件名重复互相覆盖,最终仅留存ESM格式的dist/index.js,UMD产物被完全覆盖丢失。
  4. 尝试给两个output条目配置独立的子目录作为dir(UMD输出到dist/umd,ESM输出到dist/esm),又触发插件校验报错:[!] (plugin typescript) Error: @rollup/plugin-typescript: 'outDir' must be located inside 'dir'.
    原有tsconfig配置的outDir为./dist,既不属于dist/umd也不属于dist/esm子目录,无法通过校验。
  5. 尝试删除tsconfig中的outDir配置,又触发新的校验报错:[!] (plugin typescript) Error: @rollup/plugin-typescript: 'dir' must be used when 'declarationDir' is specified.
  6. 注释掉tsconfig中的declarationDir配置后,所有校验报错消失,但无法生成符合原有目录要求的TypeScript类型声明文件。

经过多轮不同的配置组合调整,始终无法在保证原有目录结构、单文件双格式产物、正常生成类型声明的要求下跑通构建流程,暂不确定是遗漏了关键配置项,还是插件本身的校验逻辑存在适配问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.01 11:45:07