我们有 CRA React 应用程序,我们从 webpack 迁移到 Vite。
问题: 当我使用生产模式在本地运行应用程序时,出现以下错误:
1. 未捕获的类型错误:RefreshRuntime.injectIntoGlobalHook 不是函数 在(索引):6:16
第 16 行:
```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>
```
Uncaught Error: @vitejs/plugin-react can't detect preamble. Something is wrong. See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201
在 TokenContext.jsx:1:71 ````
第 1 行:
```jsx
import { createContext, useContext, useEffect, useState } from "react";
```
但是,当我们在本地运行其他模式(例如 testin、dev、staging)时,其工作正常。 我使用的浏览器没有像React dev tool这样的任何扩展。
package.json:
json
"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 节点版本:v18.19.0
根据社区反馈,删除 React 开发工具扩展似乎不起作用。 并将以下代码添加到 Index.html 似乎也不起作用。
<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>
问题出在 vite.config 文件上
我必须从 NODE_ENV 中删除模式条件
define: {
"process.env.NODE_ENV": JSON.stringify(env.NODE_ENV),
},