vite-plugin-node-stdlib-browser icon indicating copy to clipboard operation
vite-plugin-node-stdlib-browser copied to clipboard

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

Open Pinqvin opened this issue 3 years ago • 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.

Pinqvin avatar Oct 10 '22 11:10 Pinqvin

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 avatar Oct 11 '22 06:10 Pinqvin

@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 avatar Nov 18 '22 22:11 danielholmes

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

xpluscal avatar Dec 16 '22 23:12 xpluscal

@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.

danielholmes avatar Dec 16 '22 23:12 danielholmes

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

xpluscal avatar Dec 22 '22 09:12 xpluscal