gpt4 book ai didi

reactjs - 从 CRA(create react app) 迁移到 vite 后,未定义缓冲区

转载 作者:行者123 更新时间:2023-12-05 05:51:36 25 4
gpt4 key购买 nike

在声明并完成所有配置文件后,当我启动服务器时,我得到 Buffer not defined 并且错误指向一个 npm 模块。 Uncaught ReferenceError :缓冲区未定义在 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.更新index.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>

关于reactjs - 从 CRA(create react app) 迁移到 vite 后,未定义缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70354248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com