如何在Vite应用中使用Buffer、处理?

问题描述 投票:0回答:2

我在 Vite 的 Typescript React 应用程序设置中使用 wagmi。

我遇到了一些问题,例如:

“全局未定义”,“缓冲区未定义”

我用 main.tsx 中的一些代码再次尝试了它:

import { Buffer } from 'buffer';
import process from 'process';

window.global = window;
window.Buffer = Buffer;
window.process = process;

但是我仍然遇到一些错误,例如: “为了浏览器兼容性,模块“process”已被外部化。无法在客户端代码中访问“process.versions”。”

连接到 coinbase 或 walletconnect 连接器时会出现错误。

我的vite.config.ts

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
//import Buffer from 'buffer';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    port: 5000,
  },
  resolve: {
    alias: [{ find: '@', replacement: '/src' }],
  },
  define: {
    // global: 'window',
    // Buffer: Buffer,
    // process: process,
  },
});
reactjs typescript vite web3js
2个回答
0
投票

要使 bufferprocess 正常工作,请执行以下操作:

  1. 安装缓冲区并处理:

    npm install buffer process

  2. 编辑

    index.html
    添加一些js:

<!-- node // buffer-->
<script>window.global = window;</script>
<script type="module">
    import { Buffer } from "buffer/"; // <-- no typo here ("/")
    import process from "process";
   
    window.Buffer = Buffer;
    window.process = process;
</script>
  1. 编辑您的
    vite.config.js
    以添加
    resolve.alias
    选项:
export default defineConfig({
  [...]

  resolve: {
    alias: {
      process: "process/browser"
    }
  }
})
  1. 在您的组件中,导入缓冲区(注意
    /
    ):
import { Buffer } from 'buffer/'

[...]

stackblitz上的实时示例,在预览中打开控制台开发工具,然后查看

Uint8Array
调试行。

您可以阅读我的旧答案以进行进一步设置,例如流程、事件甚至加密。


0
投票

很多人在这里问同样的问题,但我找不到正确的答案。 然而,几天前我发现了完美答案

我们有时会在 vite 应用中遇到错误 “流程未定义”这是因为 Vite 不会自动填充 Node.js 模块。

https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility

答案https://www.npmjs.com/package/vite-plugin-node-polyfills

它说

由于浏览器不支持 Node 的核心模块,因此使用的包 它们必须经过多填充才能在浏览器环境中运行。在一个 尝试防止运行时错误,Vite 会产生错误或警告 当您的代码引用内置模块(例如 fs 或 path)时。

解决方案:

  1. 将包安装为开发依赖项。

npm install --save-dev vite-plugin-node-polyfills

  1. 将插件添加到您的 vite.config.ts 文件中。

import { defineConfig, loadEnv  } from 'vite'
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import react from '@vitejs/plugin-react'

export default defineConfig(({ command, mode }) => {
  // Load env file based on `mode` in the current working directory.
  // Set the third parameter to '' to load all env regardless of the `VITE_` prefix.
  const env = loadEnv(mode, process.cwd(), '')
  return {
    plugins: [
      nodePolyfills(), // this is necessary to avoid "process is not defined issue"
      react()]
  }

})

希望这对大家有很大帮助。 祝你好运

© www.soinside.com 2019 - 2024. All rights reserved.