![](/img/trans.png)
[英]ReferenceError: React is not defined - Migrating from CRA to Vite and NX
[英]Buffer is not defined, after migrating from CRA(create react app) to vite
在聲明並完成所有配置文件后,當我啟動服務器時,我得到 Buffer not defined 並且錯誤指向 npm 模塊。 Uncaught ReferenceError: Buffer is not definedat node_modules/jsesc/jsesc.js
您可以在 vite.config.ts、index.html 和添加包中進行以下更改以解決此問題
1.安裝包
yarn add process util buffer events
yarn add @esbuild-plugins/node-modules-polyfill
2.更新vite.config
import GlobalPolyFill from "@esbuild-plugins/node-globals-polyfill";
import react from "@vitejs/plugin-react";
import { resolve } from "path";
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [react()],
optimizeDeps: {
esbuildOptions: {
define: {
global: "globalThis",
},
plugins: [
GlobalPolyFill({
process: true,
buffer: true,
}),
],
},
},
resolve: {
alias: {
process: "process/browser",
stream: "stream-browserify",
zlib: "browserify-zlib",
util: "util",
},
},
});
3.更新索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/assets/images/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
<script>
window.global = window;
</script>
<script type="module">
import process from "process";
import EventEmitter from "events";
import {Buffer} from "buffer";
window.Buffer = Buffer;
window.process = process;
window.EventEmitter = EventEmitter;
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/index.js"></script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.