我需要一种为浏览器指定 Buffer 别名的方法。
不确定哪个模块需要这个,但它可能与加密相关。
500
Buffer is not defined
@http://localhost:3000/_app/pages/index.svelte-2478ade3.js:1:111754
问题在于使用 Torus Node 库。
这是一个存储库:https://github.com/ralyodio/torus-bufer
npm i
npm run build
npm run preview
...您将看到错误。 npm run dev
工作正常,因为 Node 处理请求。问题仅在于浏览器环境。
svelte.config.js 中的 polyfill 似乎不起作用:https://github.com/ralyodio/torus-bufer/blob/master/svelte.config.js
更新:看来更大的问题是在使用 sveltekit 静态适配器执行 npm run build 时不遵守 NodeGlobalsPolyfillPlugin。
最佳答案
我必须更改 3 个文件, 在 vite.config.ts 、 index.html 中添加包
1.安装软件包
yarn install process util buffer events
yarn add @esbuild-plugins/node-modules-polyfill
2.更新vite.config
import GlobalPolyFill from "@esbuild-plugins/node-globals-polyfill";
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { resolve } from "path";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [svelte()],
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>
关于node.js - 未捕获( promise )ReferenceError : Buffer is not defined in vite/sveltekit with Torus,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72267731/