node.js - 未捕获( promise )ReferenceError : Buffer is not defined in vite/sveltekit with Torus

标签 node.js svelte vite sveltekit

我需要一种为浏览器指定 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/

相关文章:

node.js - 使用强大的和(knox 或 aws-sdk)在 Node.js 上将文件流式上传到 S3

javascript - 如何使用 expressjs、reactjs 持久化数据?

node.js - Nodejs + Cassandra 驱动程序 --- 尝试创建物化 View 时出现错误 'unconfigured table'

node.js - 如何为多个node.js应用程序设置AWS EC2?

routes - 有没有办法保存 astro 的状态

javascript - 平滑的路由链接消除了 Electron 中的基本路径

vue.js - Pinia:使用设置语法时的 $reset 替代方案

javascript - 将事件指令添加到 svelte html 表达式中?

reactjs - 如何在 ViteJS 和 React 中使用 autoprefixer?

reactjs - 在 Vercel 中部署 React 应用程序时出现 404 错误