vite - 有 vite 的 browserify 吗?如何在基于 vite 的项目中使用 webrtc-swarm?

标签 vite browserify p2p

标题已经说明了这一点。使用webrtc-swarm我相信你需要 browserify - Buffer 需要全局定义,尽管有一个方便的替代品,但仅通过添加如下代码就无法及时加载来解决其要求:

import { Buffer } from 'buffer'
globalThis.Buffer = Buffer

我从 webrtc-swarm 的自述文件中实现的用法是:

import swarm from 'webrtc-swarm'
import signalhub from 'signalhub'

  const hub = signalhub('swarm-example', [clientOpts.server])
  const swarmClient = swarm(hub)

我看到的错误是:

Uncaught (in promise) TypeError: Buffer is undefined
    js index.js:12
    __require2 chunk-TFWDKVI3.js:18
    js browser.js:15
    __require2 chunk-TFWDKVI3.js:18
    js index.js:6
    __require2 chunk-TFWDKVI3.js:18
    js index.js:1
    __require2 chunk-TFWDKVI3.js:18
    <anonymous> webrtc-swarm.js:1620

最佳答案

Vite 中没有完全等同的 browserify;相反,您可以尝试使用别名polyfills的多种策略之一。您应该首先尝试的最简单的事情是使用像 vite-plugin-node-polyfills 这样的 vite 插件或vite-plugin-node-stdlib-browser .

// vite.config.js
import { defineConfig } from 'vite'
import { nodePolyfills } from 'vite-plugin-node-polyfills'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    nodePolyfills({
      // Whether to polyfill `node:` protocol imports.
      protocolImports: true,
    }),
  ],
})

如果这不起作用,您可以尝试组合基于汇总的插件。当您希望提供 own implementation对于像 events 这样的核心 Node.js 模块,那么您可以使用 resolve.alias以及您自己的填充来实现此目的:

// vite.config.js

export default {
  resolve: {
    alias: {
      // Ensure that you install 'rollup-plugin-polyfill-node' package
      'events': 'rollup-plugin-node-polyfills/polyfills/events',
    }
}

同上rollup-plugin-node-polyfills也可以直接作为Vite插件使用:

// vite.config.js
import nodePolyfills from 'rollup-plugin-polyfill-node';

export default {
  plugins: [
    // Automatically polyfill all the core node.js modules
    // May or may not be desirable depending on the required build.
    // Also polyfill globals like `process` and `Buffer`.
    nodePolyfills({})
  ]
}

如果您的汇总插件无法以这种方式工作,您可以使用更多 low-level API使用 build.rollupOptions.plugins 配置选项来使用 rollup 插件。

最后,如果您只是想修补诸如 Bufferprocess 之类的全局对象,您可以尝试 rollup inejct插件。

On a side note, even though Vite.js uses ESBuild under the hood, ESBuild plugins cannot be used with Vite as it uses the transform API.

关于vite - 有 vite 的 browserify 吗?如何在基于 vite 的项目中使用 webrtc-swarm?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75714004/

相关文章:

javascript - 处理 angularjs 测试中的依赖关系

css - 具有通用模块 css 的 browserify-css

sockets - NAT 路由器在拒绝来自先前打开的连接的传入数据包之前等待多长时间

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

webassembly - 如何在 Vite 中使用嵌入式 Webassembly?

vue.js - 如何配置Vite开发服务器通过端口代理路径运行?

javascript - 迁移到 Vite : Uncaught TypeError: Cannot read property 'attrs' of undefined

javascript - 使用 Gulp 和 Browserify 捆绑多个文件

java - 用 Java 实现的 Bittorrent Peer Wire 协议(protocol)

java - 开发p2p小程序需要知道什么