haoqunjiang/vite-plugin-node-stdlib-browser

Can I make process and/or Buffer globally available with this plugin?

Opened this issue · 5 comments

Our project has some dependencies that expect process to be globally available (ie. it's not being imported directly). Is there a way to use this plugin and Vite configuration to make it globally available for those dependencies to use? I've solved this manually by attaching process to the window object in my own code for now, but would prefer a solution based on configuration instead, if that's possible to do.

Looks like my manual approach to solving this isn't that great. I made an example repo https://github.com/Pinqvin/vite-node-stdlib-process. Manually adding process to the window object seems to break loading React dev bundle. Production build works fine

@Pinqvin I solved this issue like so.

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import inject from '@rollup/plugin-inject'
import nodePolyfills from 'vite-plugin-node-stdlib-browser'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    inject({
      modules: { Buffer: ['buffer', 'Buffer'] }
    }),
    nodePolyfills()
  ]
})

See simple repo with the fix applied:

https://github.com/danielholmes/jimp-vite

Note that this solved the issue in the built version, there was no issue in the dev version for me.

@danielholmes how do you include process? I see you inject buffer - did you have any luck regarding getting process in? @Pinqvin

@xpluscal Using this polyfill:

https://github.com/danielholmes/jimp-vite/blob/a26dc0e4cf1bfc3c1d558794e4ef4063fae74da7/src/node-polyfills.ts

(globalThis as any).process = {
    env: {},
    versions: {}
} as any
export {};

From memory I needed to do this for the built version but it wasn't needed for the dev version.

Thank you! I'll need to see how we can make this work with Sveltekit