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

tsconfig路径别名与Rollup.js兼容问题求助

解决Rollup+TypeScript别名导致声明文件无法解析的问题

核心问题:运行时代码的别名被@rollup/plugin-alias正确替换,但生成的.d.ts文件中保留了@/my-dependency别名,导致外部项目无法解析该路径。以下是几个可行的解决思路:

方案一:在d.ts打包阶段手动替换别名

利用@rollup/plugin-replace在打包声明文件时直接替换别名路径,确保最终生成的dist/index.d.ts使用正确的相对路径:

  1. 安装依赖:
npm install @rollup/plugin-replace --save-dev
  1. 修改Rollup配置中的第二个任务:
import replace from '@rollup/plugin-replace';

export default [
  // 第一个任务(原运行时代码打包)...
  {
    input: 'dist/dts/index.d.ts',
    output: [{ file: 'dist/index.d.ts', format: 'es' }],
    plugins: [
      replace({
        preventAssignment: true,
        // 替换@/my-dependency为dist目录下对应的相对路径
        values: {
          '@/my-dependency': './dts/types/some-folder/app/index'
        }
      }),
      dts()
    ],
  },
];

注意:替换的路径需根据实际生成的文件结构调整,确保从dist/index.d.ts能正确指向目标.d.ts文件。

方案二:用TypeScript Transformer自动转换路径

通过ts-transform-paths让TypeScript在生成声明文件时自动将别名转为相对路径,从根源解决问题:

  1. 安装依赖:
npm install ts-transform-paths ttypescript --save-dev
  1. 修改tsconfig.json,添加Transformer配置:
{
  "compilerOptions": {
    // 原有配置...
    "plugins": [
      { "transform": "ts-transform-paths", "afterDeclarations": true }
    ]
  }
}
  1. 修改Rollup的typescript插件配置,指定使用ttypescript:
typescript({
  tsconfig: './tsconfig.json',
  exclude: ['**/testData/**/*', '**/*.chunk.js'],
  typescript: require('ttypescript')
}),

这样TypeScript生成.d.ts文件时会自动替换别名,后续rollup-plugin-dts打包时就能直接使用正确的相对路径。

方案三:调整rollup-plugin-typescript-paths配置

如果你之前尝试过rollup-plugin-typescript-paths但无效,可能是未开启声明文件转换:

  1. 确保插件安装正确后,修改Rollup第一个任务的插件顺序:
import typescriptPaths from 'rollup-plugin-typescript-paths';

export default [
  {
    input: 'src/index.ts',
    // ...其他配置
    plugins: [
      typescriptPaths({
        tsconfig: './tsconfig.json',
        // 开启声明文件的路径转换
        transformDeclarations: true
      }),
      alias({
        entries: [{ find: '@/my-dependency', replacement: './src/types/some-folder/app/index' }],
      }),
      // ...其他插件(external、resolve等)
      typescript({
        tsconfig: './tsconfig.json',
        exclude: ['**/testData/**/*', '**/*.chunk.js'],
      }),
      // ...其他插件
    ],
  },
  // 第二个任务...
];

该插件会同时处理运行时代码和声明文件中的别名路径,确保两者一致。


内容的提问来源于stack exchange,提问作者Divide by Zero

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:01:13