Search code examples
vitebrowserifyp2p

is there a browserify for vite? how can I use webrtc-swarm with a vite based project?


The title about says it. To use webrtc-swarm I believe that you need browserify -- Buffer is needed to be globally defined, and although there is a handy replacement, it won't load in time to resolve its requirement just by adding code like:

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

The usage that I implemented from webrtc-swarm's readme is:

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

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

the error that I see is:

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

Solution

  • There isn't exactly a browserify equivalent in Vite; instead you can try one of the multiple strategies with aliases and polyfills. The simplest thing you should try first is using a vite plugin like vite-plugin-node-polyfills or 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,
        }),
      ],
    })
    

    If this doesn't work then, you can try combination of rollup based plugins. When you wish to provide own implementation for a core node.js module like events, then you can use resolve.alias along with your own polyfill to achieve this:

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

    The same rollup-plugin-node-polyfills can also be used as direct Vite plugin:

    // 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({})
      ]
    }
    

    If your rollup plugin doesn't work this way, you can use more low-level API to use rollup plugin using build.rollupOptions.plugins configuration options.

    Finally, if you are just looking to patch global objects like Buffer and process, you can try rollup inejct plugin.

    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.