未捕获(承诺中)ReferenceError:未使用 Torus 在 vi​​te/sveltekit 中定义缓冲区

cho*_*ovy 2 node.js svelte vite sveltekit

我需要一种为浏览器指定 Buffer 别名的方法。

不确定哪个模块需要这个,但它可能与加密相关。

500

Buffer is not defined

@http://localhost:3000/_app/pages/index.svelte-2478ade3.js:1:111754

Run Code Online (Sandbox Code Playgroud)

问题在于使用 Torus 节点库。

这是一个存储库: https: //github.com/ralyodio/torus-bufer

npm i
npm run build
npm run preview
Run Code Online (Sandbox Code Playgroud)

...你会看到错误。npm run dev由于节点处理请求,因此工作正常。问题仅在于浏览器环境。

中的polyfillsvelte.config.js似乎不起作用:https ://github.com/ralyodio/torus-bufer/blob/master/svelte.config.js

更新:所以看起来更大的问题是,在使用 sveltekit 静态适配器进行 npm run build 时,不遵守 NodeGlobalsPolyfillPlugin 。

Gou*_*J.M 5

我必须在 vite.config.ts 、index.html 中的 3 个文件中进行更改并添加包

1.安装包

yarn install process util buffer events
yarn add @esbuild-plugins/node-modules-polyfill
Run Code Online (Sandbox Code Playgroud)

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",
        },
    },
});

Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)