从Webpack迁移到Vite的CRA React项目生产模式启动报错求助
Vite生产模式本地运行时的React刷新相关错误
问题背景
我们有一个从CRA迁移到Vite的React项目,本地运行testing、dev、staging模式均正常,但prod模式启动时出现两类错误:
错误1:RefreshRuntime.injectIntoGlobalHook is not a function
报错位置在(index):6:16,对应index.html中的代码片段:
<!DOCTYPE html> <html lang="en"> <head> <script type="module"> import RefreshRuntime from "/@react-refresh" RefreshRuntime.injectIntoGlobalHook(window) window.$RefreshReg$ = () => {} window.$RefreshSig$ = () => (type) => type window.__vite_plugin_react_preamble_installed__ = true </script> </head> </html>
错误2:@vitejs/plugin-react can't detect preamble. Something is wrong.
报错位置在TokenContext.jsx:1:71,对应代码第一行:
import { createContext, useContext, useEffect, useState } from "react";
相关配置信息
package.json scripts字段
"scripts": { "start": "vite", "staging": "vite --mode staging", "dev": "vite --mode development", "testing": "vite --mode testing", "prod": "vite --mode production", "build": "vite build", "test": "vite test", "test:coverage": "vite test --collectCoverage --watchAll", "eject": "vite eject", "stylelint": "stylelint \"**/*.scss\"", "eslint": "npx eslint ./src --max-warnings=2", "eslint:fix": "npx eslint ./src --fix", "build:dev": "vite build --outDir dist/development --mode development", "build:test": "vite build --outDir dist/testing --mode testing", "build:staging": "vite build --outDir dist/staging --mode staging", "build:prod": "vite build --outDir dist/production --mode production", "build-all": "npm-run-all --parallel build:*", "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview" },
vite.config.mjs配置
export default ({ mode }) => { const env = loadEnv(mode, process.cwd()); return defineConfig({ build: { outDir: 'build', chunkSizeWarningLimit: 2000, }, plugins: [ react(), svgrPlugin({ svgrOptions: { icon: true, } }), ], envDir: "./src/environments", define: { "process.env.NODE_ENV": JSON.stringify(env.NODE_ENV || mode), }, server: { port: 3000, }, }); };
系统信息
- Vite版本:
^4.2.1 - 操作系统:Windows 11
- Node版本:
v18.19.0
已尝试的无效方案
- 移除React DevTools扩展
- 在
index.html中手动添加React刷新相关的script代码
解决建议
删除index.html中手动添加的React刷新script
生产模式下Vite不会启用React热刷新,这段代码是dev模式下插件自动注入的,手动添加会导致生产环境找不到/@react-refresh模块,直接删除即可。明确禁用生产环境的React热刷新
修改vite.config.mjs中的react插件配置,仅在非生产模式启用热刷新:plugins: [ react({ fastRefresh: mode !== 'production' }), svgrPlugin({ svgrOptions: { icon: true, } }), ]修正process.env.NODE_ENV的定义
确保生产模式下process.env.NODE_ENV为"production",避免插件误判运行环境:define: { "process.env.NODE_ENV": JSON.stringify(mode === 'production' ? 'production' : env.NODE_ENV || mode), },采用正确的生产环境启动方式
生产模式应先构建再预览:执行npm run build:prod构建产物,再用vite preview启动预览服务。若坚持用vite --mode production启动,先删除node_modules/.vite缓存目录后再重新启动。
内容的提问来源于stack exchange,提问作者Aseel GA
相关产品推荐
相关产品推荐

