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

从CRA迁移至Vite遇问题:无法确定当前Node.js版本

问题:React项目从CRA迁移至Vite后构建完成但页面空白,控制台报错

迁移后构建可正常完成,但页面显示空白,控制台报错如下:

@emotion_styled_macro.js:32600 Uncaught TypeError: Unable to determine current node version
    at versionIncluded (@emotion_styled_macro.js:32600:15)
    at isCore (@emotion_styled_macro.js:32614:33)
    at node_modules/resolve/lib/core.js (@emotion_styled_macro.js:33117:22)
    at __require2 (chunk-XZ6WXOVE.js?v=dcdf163e:2132:50)
    at node_modules/resolve/index.js (@emotion_styled_macro.js:33350:18)
    at __require2 (chunk-XZ6WXOVE.js?v=dcdf163e:2132:50)
    at node_modules/babel-plugin-macros/dist/index.js (@emotion_styled_macro.js:43001:21)
    at __require2 (chunk-XZ6WXOVE.js?v=dcdf163e:2132:50)
    at node_modules/@emotion/babel-plugin/dist/emotion-babel-plugin.esm.js (@emotion_styled_macro.js:43851:42)
    at __init (chunk-XZ6WXOVE.js?v=dcdf163e:2129:56)

项目情况:

  • CRA环境下运行正常,仅通过Chakra UI依赖使用emotion,不愿替换Chakra UI
  • 已搜索相关内容未找到同类问题或解决方案
  • 曾推测是ESBuild与Babel转换流程差异,尝试复刻CRA的Babel配置但无效

当前Vite配置:

export default defineConfig({
  build: {
    target: browserslistToEsbuild(),
  },
  plugins: [react({
    jsxImportSource: '@emotion/react',
    babel: {
    plugins: ['@emotion/babel-plugin'],
    },
    }),nodePolyfills({
    protocolImports: true,
    overrides: {
      // Since `fs` is not supported in browsers, we can use the `memfs` package to polyfill it.
      fs: 'memfs',
    }
  }),
  legacy({
    targets: ['defaults', 'not IE 11'],
  }),
  babel({
    babelConfig:{
      presets:['@babel/preset-react']
    }
  }),
  ],
})

解决方案

  • 移除配置中重复的babel插件:@vitejs/plugin-react已经内置了Babel处理逻辑,额外添加babel插件会导致冲突,引发emotion相关的异常
  • 统一@emotion依赖版本:确保@emotion/react、@emotion/styled、@emotion/babel-plugin版本一致,建议升级到最新稳定版,执行命令:
    npm update @emotion/react @emotion/styled @emotion/babel-plugin
    
  • 简化Vite配置,调整后的配置如下:
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    import { browserslistToEsbuild } from 'vite-plugin-browserslist';
    
    export default defineConfig({
      build: {
        target: browserslistToEsbuild(),
      },
      plugins: [
        react({
          jsxImportSource: '@emotion/react',
          babel: {
            plugins: ['@emotion/babel-plugin'],
          },
        }),
        // 仅保留必要的polyfill,若项目无node核心模块依赖可移除nodePolyfills
        // nodePolyfills({
        //   protocolImports: true,
        //   overrides: {
        //     fs: 'memfs',
        //   }
        // }),
        legacy({
          targets: ['defaults', 'not IE 11'],
        }),
      ],
    });
    
  • 清理构建缓存:删除项目根目录下的node_modules/.vite和dist文件夹,再重新执行构建命令
  • 检查项目中是否手动安装了babel-plugin-macros,若有则卸载,Chakra UI依赖的emotion不需要单独安装该插件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 05:33:26