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

将Rush Monorepo从create-react-app迁移至Vite时的别名配置问题

解决Rush Monorepo迁移Vite时链接包别名的类型导出问题

问题背景

在将Rush Monorepo从Create React App迁移到Vite的过程中,配置@projectName/api-types包别名后执行vite build时出现错误:

src/containers/actionItems/helpers.ts (9:9): "type" is not exported by "../../packages/api-types/build/index.js"

该类型实际存在于api-types包的嵌套导入文件中,且已尝试过更新tsconfig paths、配置optimizeDeps、调整build.commonJsOptions等方法,但问题仍未解决。

项目目录结构:

Project
- apps
  - frontend
  - backend
- packages
  - api-types

frontend的package.json依赖:

"dependencies": {
  "@projectName/api-types": "workspace:*",
}

原Vite别名配置:

resolve: {
  alias: {
    "@projectName/api-types": path.resolve(
      __dirname,
      "../../packages/api-types/build/index.js"
    ),
  }
}

api-types的build产物代码:

Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./account"), exports);

问题分析

直接将别名指向build后的JS文件会导致Vite无法正确识别__exportStar导出的嵌套类型,同时如果包的类型声明配置不完整,也会加剧这个问题。

解决方案

1. 修改Vite别名指向包根目录而非build产物

不要直接指定到build后的JS文件,让Vite通过包的package.json入口字段自动解析:

// frontend/vite.config.js
const path = require('path');

export default {
  resolve: {
    alias: {
      "@projectName/api-types": path.resolve(__dirname, "../../packages/api-types"),
    },
  },
};

2. 完善api-types包的配置

确保packages/api-types/package.json中包含正确的入口和类型声明字段:

{
  "name": "@projectName/api-types",
  "main": "./build/index.js",
  "types": "./build/index.d.ts", // 必须指定类型声明文件路径
  "scripts": {
    "build": "tsc" // 确保TypeScript编译时生成声明文件
  }
}

3. 确保api-types的tsconfig生成类型声明

修改packages/api-types/tsconfig.json,开启类型声明生成:

{
  "compilerOptions": {
    "declaration": true, // 生成.d.ts文件
    "declarationDir": "./build", // 声明文件输出目录
    "outDir": "./build",
    "module": "ESNext",
    "target": "ESNext",
    "strict": true
  },
  "include": ["src/**/*"]
}

4. 同步frontend的tsconfig路径配置

在apps/frontend/tsconfig.json中添加paths配置,让TypeScript正确识别类型:

{
  "compilerOptions": {
    // 其他配置...
    "paths": {
      "@projectName/api-types": ["../../packages/api-types/build/index.d.ts"]
    }
  }
}

5. 优化Vite的CommonJS处理(可选)

如果仍有CommonJS导出识别问题,调整Vite的build配置:

export default {
  build: {
    commonjsOptions: {
      include: [/api-types/, /node_modules/],
      sourceMap: false
    }
  }
};

完成以上配置后,重新执行vite build即可解决类型导出的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 18:15:01