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

Vite构建npm workspace React项目时出现R2不是函数错误

问题:Vite构建后出现Uncaught TypeError: R2 is not a function错误

项目结构

/apps
    /fe-app
/common
    /common
    /common-fe
  • common-fe依赖common
  • fe-app依赖common-fe

背景

此前使用CRA搭配babel/webpack打包,近期切换到Vite。公共包不参与打包,开发时通过tsc -w监听编译,打包前执行tsc -b完成编译。

错误现象

  • 执行vite(开发模式)时一切正常
  • 执行vite build构建成功,但用vite preview预览时,浏览器抛出Uncaught TypeError: R2 is not a function错误(R2标识在不同环境下较为稳定)
  • 堆栈追踪显示错误与ApolloClient库相关

关键配置信息

tsconfig(所有项目通用配置)

  • "target": "ES2022"
  • "module": "ESNext"
  • "moduleResolution": "Node"
  • "useDefineForClassFields": true
  • "emitDecoratorMetadata": true
  • fe-app的paths指向common-fe
  • common-fe的paths指向common

package.json

  • fe-app通过文件系统依赖common-fe
  • common-fe通过文件系统依赖common

Vite配置(fe-app)

plugins: [
    tsconfigPaths(),
    react({ tsDecorators: true })
],
resolve: {
    alias: {
        '@': resolve(__dirname, './src'),
        'common-fe': resolve(__dirname, '../../common/common-fe/src'),
        'common': resolve(__dirname, '../../common/common')
    }
}

解决思路

  1. 检查公共包编译输出

    • 确认common和common-fe的tsconfig.json中outDir配置正确,编译后的模块格式(ES模块)与Vite构建产物兼容
    • 检查编译后的文件是否存在导出/导入语法错误,比如默认导出与命名导出混用导致的识别异常
  2. 排查ApolloClient兼容性

    • 统一fe-app、common-fe中ApolloClient及相关依赖(如graphql)的版本,避免跨版本依赖冲突
    • 在Vite配置中添加ApolloClient相关优化,确保CommonJS格式依赖被正确转换:
      export default defineConfig({
        optimizeDeps: {
          include: ['@apollo/client', 'graphql']
        },
        build: {
          commonjsOptions: {
            include: [/node_modules/, /common/, /common-fe/]
          }
        }
      })
      
  3. 验证路径解析逻辑

    • 移除Vite配置中手动添加的common和common-fe别名,仅保留tsconfigPaths()插件,避免路径解析冲突
    • 调整tsconfig.json的paths配置,指向公共包编译后的输出目录而非源码目录(打包时公共包已编译完成,应使用编译后的文件)
  4. 开启构建调试

    • 执行vite build --debug查看构建日志,定位R2对应的原始模块
    • 检查构建产物中R2对应的代码,确认是哪个导出被错误识别为非函数类型
  5. 检查装饰器配置

    • 确认emitDecoratorMetadata与Vite的react({ tsDecorators: true })配置匹配,避免装饰器处理导致的类/函数导出异常

内容的提问来源于stack exchange,提问作者Radek Domański

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 00:48:25