Skip to content

Instantly share code, notes, and snippets.

@FbN
Last active April 18, 2024 08:36
Show Gist options
  • Star 46 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save FbN/0e651105937c8000f10fefdf9ec9af3d to your computer and use it in GitHub Desktop.
Save FbN/0e651105937c8000f10fefdf9ec9af3d to your computer and use it in GitHub Desktop.
vite.config.js node built-in polyfills
// yarn add --dev @esbuild-plugins/node-globals-polyfill
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
// yarn add --dev @esbuild-plugins/node-modules-polyfill
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'
// You don't need to add this to deps, it's included by @esbuild-plugins/node-modules-polyfill
import rollupNodePolyFill from 'rollup-plugin-node-polyfills'
export default {
resolve: {
alias: {
// This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill,
// see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts
// process and buffer are excluded because already managed
// by node-globals-polyfill
util: 'rollup-plugin-node-polyfills/polyfills/util',
sys: 'util',
events: 'rollup-plugin-node-polyfills/polyfills/events',
stream: 'rollup-plugin-node-polyfills/polyfills/stream',
path: 'rollup-plugin-node-polyfills/polyfills/path',
querystring: 'rollup-plugin-node-polyfills/polyfills/qs',
punycode: 'rollup-plugin-node-polyfills/polyfills/punycode',
url: 'rollup-plugin-node-polyfills/polyfills/url',
string_decoder:
'rollup-plugin-node-polyfills/polyfills/string-decoder',
http: 'rollup-plugin-node-polyfills/polyfills/http',
https: 'rollup-plugin-node-polyfills/polyfills/http',
os: 'rollup-plugin-node-polyfills/polyfills/os',
assert: 'rollup-plugin-node-polyfills/polyfills/assert',
constants: 'rollup-plugin-node-polyfills/polyfills/constants',
_stream_duplex:
'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',
_stream_passthrough:
'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',
_stream_readable:
'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',
_stream_writable:
'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',
_stream_transform:
'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',
timers: 'rollup-plugin-node-polyfills/polyfills/timers',
console: 'rollup-plugin-node-polyfills/polyfills/console',
vm: 'rollup-plugin-node-polyfills/polyfills/vm',
zlib: 'rollup-plugin-node-polyfills/polyfills/zlib',
tty: 'rollup-plugin-node-polyfills/polyfills/tty',
domain: 'rollup-plugin-node-polyfills/polyfills/domain'
}
},
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
process: true,
buffer: true
}),
NodeModulesPolyfillPlugin()
]
}
},
build: {
rollupOptions: {
plugins: [
// Enable rollup polyfills plugin
// used during production bundling
rollupNodePolyFill()
]
}
}
}
@GiancarlosIO
Copy link

hi guys @Tbaut @jeffhu1 does any one know why it is necessary to also add the rollupNodePolyFill() if we are already configuring the aliases manually? 🤔
maybe the config.resolve.alias are ignored in production?

@dickeylth
Copy link

Actually, I found that although including buffer and process aliases made the production build work, it broke the development server. The final solution I found that fixed both was this: vitejs/vite#3817 (comment) It's incredible that something non-development related costed so much headache

Thank you very much for saving my life!

@sadiqsalau
Copy link

sadiqsalau commented Dec 21, 2022

/**
 * pnpm add -D esbuild-plugins-node-modules-polyfill rollup-plugin-polyfill-node
 */
import nodePolyfills from "rollup-plugin-polyfill-node";
import { defineConfig } from "vite";
import { nodeModulesPolyfillPlugin } from "esbuild-plugins-node-modules-polyfill";

export default defineConfig({
  optimizeDeps: {
    esbuildOptions: {
      // Enable esbuild polyfill plugins
      plugins: [nodeModulesPolyfillPlugin()],
    },
  },
  build: {
    rollupOptions: {
      plugins: [nodePolyfills()],
    },
  },
});

@xpluscal
Copy link

/**
 * pnpm add -D esbuild-plugins-node-modules-polyfill rollup-plugin-node-externals
 */
import { nodeModulesPolyfillPlugin } from 'esbuild-plugins-node-modules-polyfill';
import externals from "rollup-plugin-node-externals";

export default {
  optimizeDeps: {
    esbuildOptions: {
      // Enable esbuild polyfill plugins
      plugins: [
        nodeModulesPolyfillPlugin(),
      ],
    },
  },
  build: {
    rollupOptions: {
      plugins: [
        externals()
      ],
    },
  },
};

Hey @sadiqsalau this looks promising - have you tried this with vite 4?

@sadiqsalau
Copy link

@xpluscal Yes..

@sadiqsalau
Copy link

@xpluscal I have updated the code. Previous polyfill builds successfully but throws error on live site. Use this now:

/**
 * pnpm add -D esbuild-plugins-node-modules-polyfill rollup-plugin-polyfill-node
 */
import nodePolyfills from "rollup-plugin-polyfill-node";
import { defineConfig } from "vite";
import { nodeModulesPolyfillPlugin } from "esbuild-plugins-node-modules-polyfill";

export default defineConfig({
  optimizeDeps: {
    esbuildOptions: {
      // Enable esbuild polyfill plugins
      plugins: [nodeModulesPolyfillPlugin()],
    },
  },
  build: {
    rollupOptions: {
      plugins: [nodePolyfills()],
    },
  },
});

@gokhantaskan
Copy link

I'm trying to implement web3auth https://web3auth.io/docs/quick-start

None of the solutions above works for me.

versions:

"vue": "^3.2.45",
"vite": "^4.0.0",
"@esbuild-plugins/node-globals-polyfill": "^0.1.1",
"@esbuild-plugins/node-modules-polyfill": "^0.1.4",
"rollup-plugin-node-polyfills": "^0.2.1"

@Terkea
Copy link

Terkea commented Jan 24, 2023

Is anyone having this error?

✘ [ERROR] The injected path "/Users/marian/code/OzoneV2/app-web/node_modules/@esbuild-plugins/node-globals-polyfill/_buffer.js" cannot be marked as external

✘ [ERROR] The injected path "/Users/marian/code/OzoneV2/app-web/node_modules/@esbuild-plugins/node-globals-polyfill/_virtual-process-polyfill_.js" cannot be marked as external

Build failed with 2 errors:
error: The injected path "/Users/marian/code/OzoneV2/app-web/node_modules/@esbuild-plugins/node-globals-polyfill/_buffer.js" cannot be marked as external
error: The injected path "/Users/marian/code/OzoneV2/app-web/node_modules/@esbuild-plugins/node-globals-polyfill/_virtual-process-polyfill_.js" cannot be marked as external

@factiondavid
Copy link

Yes I'm dealing with this issue. Have you figured it out a solution?

@thantos
Copy link

thantos commented Jan 25, 2023

Just got this working, see comment here and the issue/comments it links to.
remorses/esbuild-plugins#27 (comment)

@6abotage
Copy link

6abotage commented Jan 25, 2023

What worked for me (dev+prod) is:

package.json

    "buffer": "^6.0.3",
    "events": "^3.3.0",
    "process": "^0.11.10",
    "url": "^0.11.0"

index.html

  <script type="module">
      import process from "process"
      import { Buffer } from "buffer"
      window.global = window
      window.Buffer = Buffer
      window.process = process
    </script>

and vite.config.js

import eslint from "@nabla/vite-plugin-eslint"
import react from '@vitejs/plugin-react-swc'

import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [react(),eslint()]
})

@Terkea
Copy link

Terkea commented Jan 26, 2023

What worked for me (dev+prod) is:

package.json

    "buffer": "^6.0.3",
    "events": "^3.3.0",
    "process": "^0.11.10",
    "url": "^0.11.0"

index.html

  <script type="module">
      import process from "process"
      import { Buffer } from "buffer"
      window.global = window
      window.Buffer = Buffer
      window.process = process
    </script>

and vite.config.js

import eslint from "@nabla/vite-plugin-eslint"
import react from '@vitejs/plugin-react-swc'

import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [react(),eslint()]
})

Doesn't seem to work for me

browser-external:stream:9 Module "stream" has been externalized for browser compatibility. Cannot access "stream.prototype" in client code.
get @ browser-external:stream:9
inherits @ inherits_browser.js:6
node_modules/jws/lib/data-stream.js @ data-stream.js:39
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jws/lib/sign-stream.js @ sign-stream.js:3
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jws/index.js @ index.js:2
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/decode.js @ decode.js:1
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/verify.js @ verify.js:4
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/index.js @ index.js:2
__require @ chunk-RSJERJUL.js?v=e3a21887:3
(anonymous) @ index.js:12
inherits_browser.js:6 Uncaught TypeError: Object prototype may only be an Object or null: undefined
    at Function.create (<anonymous>)
    at Object.inherits (inherits_browser.js:6:31)
    at node_modules/jws/lib/data-stream.js (data-stream.js:39:6)
    at __require (chunk-RSJERJUL.js?v=e3a21887:3:50)
    at node_modules/jws/lib/sign-stream.js (sign-stream.js:3:18)
    at __require (chunk-RSJERJUL.js?v=e3a21887:3:50)
    at node_modules/jws/index.js (index.js:2:18)
    at __require (chunk-RSJERJUL.js?v=e3a21887:3:50)
    at node_modules/jsonwebtoken/decode.js (decode.js:1:11)
    at __require (chunk-RSJERJUL.js?v=e3a21887:3:50)
inherits @ inherits_browser.js:6
node_modules/jws/lib/data-stream.js @ data-stream.js:39
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jws/lib/sign-stream.js @ sign-stream.js:3
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jws/index.js @ index.js:2
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/decode.js @ decode.js:1
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/verify.js @ verify.js:4
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/index.js @ index.js:2
__require @ chunk-RSJERJUL.js?v=e3a21887:3
(anonymous) @ index.js:12

@6abotage
Copy link

What worked for me (dev+prod) is:
package.json

    "buffer": "^6.0.3",
    "events": "^3.3.0",
    "process": "^0.11.10",
    "url": "^0.11.0"

index.html

  <script type="module">
      import process from "process"
      import { Buffer } from "buffer"
      window.global = window
      window.Buffer = Buffer
      window.process = process
    </script>

and vite.config.js

import eslint from "@nabla/vite-plugin-eslint"
import react from '@vitejs/plugin-react-swc'

import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [react(),eslint()]
})

Doesn't seem to work for me

browser-external:stream:9 Module "stream" has been externalized for browser compatibility. Cannot access "stream.prototype" in client code.
get @ browser-external:stream:9
inherits @ inherits_browser.js:6
node_modules/jws/lib/data-stream.js @ data-stream.js:39
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jws/lib/sign-stream.js @ sign-stream.js:3
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jws/index.js @ index.js:2
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/decode.js @ decode.js:1
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/verify.js @ verify.js:4
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/index.js @ index.js:2
__require @ chunk-RSJERJUL.js?v=e3a21887:3
(anonymous) @ index.js:12
inherits_browser.js:6 Uncaught TypeError: Object prototype may only be an Object or null: undefined
    at Function.create (<anonymous>)
    at Object.inherits (inherits_browser.js:6:31)
    at node_modules/jws/lib/data-stream.js (data-stream.js:39:6)
    at __require (chunk-RSJERJUL.js?v=e3a21887:3:50)
    at node_modules/jws/lib/sign-stream.js (sign-stream.js:3:18)
    at __require (chunk-RSJERJUL.js?v=e3a21887:3:50)
    at node_modules/jws/index.js (index.js:2:18)
    at __require (chunk-RSJERJUL.js?v=e3a21887:3:50)
    at node_modules/jsonwebtoken/decode.js (decode.js:1:11)
    at __require (chunk-RSJERJUL.js?v=e3a21887:3:50)
inherits @ inherits_browser.js:6
node_modules/jws/lib/data-stream.js @ data-stream.js:39
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jws/lib/sign-stream.js @ sign-stream.js:3
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jws/index.js @ index.js:2
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/decode.js @ decode.js:1
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/verify.js @ verify.js:4
__require @ chunk-RSJERJUL.js?v=e3a21887:3
node_modules/jsonwebtoken/index.js @ index.js:2
__require @ chunk-RSJERJUL.js?v=e3a21887:3
(anonymous) @ index.js:12

can you send me your repo for reproduction? I can check it out when I‘m home

@Terkea
Copy link

Terkea commented Jan 26, 2023

    "buffer": "^6.0.3",
    "events": "^3.3.0",
    "process": "^0.11.10",
    "url": "^0.11.0"

Cheers mate, here you have it https://stackblitz.com/edit/vitejs-vite-cizeph?file=vite.config.ts&terminal=dev

@6abotage
Copy link

    "buffer": "^6.0.3",
    "events": "^3.3.0",
    "process": "^0.11.10",
    "url": "^0.11.0"

Cheers mate, here you have it https://stackblitz.com/edit/vitejs-vite-cizeph?file=vite.config.ts&terminal=dev

You can just install the util package in your code with npm install util. It then shows a different error related to TypeScript. As I'm not familiar with TypeScript unfortunately, I can't help you further than that

@nivethan-me
Copy link

https://github.com/sodatea/vite-plugin-node-stdlib-browser

This worked for the Uncaught TypeError: util.inherits is not a function. error, thank you!

@Terkea
Copy link

Terkea commented Jan 27, 2023

https://github.com/sodatea/vite-plugin-node-stdlib-browser

This worked for the Uncaught TypeError: util.inherits is not a function. error, thank you!

Does not work for me

// vite.config.js
import { defineConfig } from "vite";
import nodePolyfills from "vite-plugin-node-stdlib-browser";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
    plugins: [nodePolyfills(), tsconfigPaths(), react()],
});

error

✘ [ERROR] The injected path "/Users/marian/code/OzoneV2/app-web/node_modules/node-stdlib-browser/helpers/esbuild/shim.js" cannot be marked as external

Build failed with 1 error:
error: The injected path "/Users/marian/code/OzoneV2/app-web/node_modules/node-stdlib-browser/helpers/esbuild/shim.js" cannot be marked as external
Failed to load url /node_modules/util/url (resolved id: /node_modules/util/url). Does the file exist?
Failed to load url /node_modules/util/searchAndFilters (resolved id: /node_modules/util/searchAndFilters). Does the file exist?
Failed to load url /node_modules/util/markerFiller (resolved id: /node_modules/util/markerFiller). Does the file exist?
Failed to load url /node_modules/util/markerFiller (resolved id: /node_modules/util/markerFiller). Does the file exist? (x2)
Failed to load url /node_modules/util/markerFiller (resolved id: /node_modules/util/markerFiller). Does the file exist? (x3)

@Terkea
Copy link

Terkea commented Jan 27, 2023

found a solution that works for me

        "@esbuild-plugins/node-globals-polyfill": "0.2.3",
        "@esbuild-plugins/node-modules-polyfill": "0.2.2",
        "rollup-plugin-node-polyfills": "^0.2.1",
        "util": "^0.12.5",

vite.config.ts

// yarn add --dev @esbuild-plugins/node-globals-polyfill
import { NodeGlobalsPolyfillPlugin } from "@esbuild-plugins/node-globals-polyfill";
// yarn add --dev @esbuild-plugins/node-modules-polyfill
import { NodeModulesPolyfillPlugin } from "@esbuild-plugins/node-modules-polyfill";
// You don't need to add this to deps, it's included by @esbuild-plugins/node-modules-polyfill
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";

export default {
    plugins: [
        react(),
        tsconfigPaths(),
        {
            name: "fix-node-globals-polyfill",
            setup(build) {
                build.onResolve({ filter: /util\.js/ }, ({ path }) => ({ path }));
            },
        },
    ],
    resolve: {
        alias: {
            // This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill,
            // see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts
            // process and buffer are excluded because already managed
            // by node-globals-polyfill
            util: "util",
            sys: "util",
            events: "rollup-plugin-node-polyfills/polyfills/events",
            stream: "rollup-plugin-node-polyfills/polyfills/stream",
            path: "rollup-plugin-node-polyfills/polyfills/path",
            querystring: "rollup-plugin-node-polyfills/polyfills/qs",
            punycode: "rollup-plugin-node-polyfills/polyfills/punycode",
            url: "rollup-plugin-node-polyfills/polyfills/url",
            string_decoder: "rollup-plugin-node-polyfills/polyfills/string-decoder",
            http: "rollup-plugin-node-polyfills/polyfills/http",
            https: "rollup-plugin-node-polyfills/polyfills/http",
            os: "rollup-plugin-node-polyfills/polyfills/os",
            assert: "rollup-plugin-node-polyfills/polyfills/assert",
            constants: "rollup-plugin-node-polyfills/polyfills/constants",
            _stream_duplex: "rollup-plugin-node-polyfills/polyfills/readable-stream/duplex",
            _stream_passthrough: "rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough",
            _stream_readable: "rollup-plugin-node-polyfills/polyfills/readable-stream/readable",
            _stream_writable: "rollup-plugin-node-polyfills/polyfills/readable-stream/writable",
            _stream_transform: "rollup-plugin-node-polyfills/polyfills/readable-stream/transform",
            timers: "rollup-plugin-node-polyfills/polyfills/timers",
            console: "rollup-plugin-node-polyfills/polyfills/console",
            vm: "rollup-plugin-node-polyfills/polyfills/vm",
            zlib: "rollup-plugin-node-polyfills/polyfills/zlib",
            tty: "rollup-plugin-node-polyfills/polyfills/tty",
            domain: "rollup-plugin-node-polyfills/polyfills/domain",
        },
    },
    optimizeDeps: {
        esbuildOptions: {
            // Node.js global to browser globalThis
            define: {
                global: "globalThis",
            },
            // Enable esbuild polyfill plugins
            plugins: [
                NodeGlobalsPolyfillPlugin({
                    process: true,
                    buffer: true,
                }),
                NodeModulesPolyfillPlugin(),
            ],
        },
    },
    build: {
        rollupOptions: {
            plugins: [
                // Enable rollup polyfills plugin
                // used during production bundling
                rollupNodePolyFill(),
            ],
        },
    },
};

@factiondavid
Copy link

found a solution that works for me

        "@esbuild-plugins/node-globals-polyfill": "0.2.3",
        "@esbuild-plugins/node-modules-polyfill": "0.2.2",
        "rollup-plugin-node-polyfills": "^0.2.1",
        "util": "^0.12.5",

vite.config.ts

// yarn add --dev @esbuild-plugins/node-globals-polyfill
import { NodeGlobalsPolyfillPlugin } from "@esbuild-plugins/node-globals-polyfill";
// yarn add --dev @esbuild-plugins/node-modules-polyfill
import { NodeModulesPolyfillPlugin } from "@esbuild-plugins/node-modules-polyfill";
// You don't need to add this to deps, it's included by @esbuild-plugins/node-modules-polyfill
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";

export default {
    plugins: [
        react(),
        tsconfigPaths(),
        {
            name: "fix-node-globals-polyfill",
            setup(build) {
                build.onResolve({ filter: /util\.js/ }, ({ path }) => ({ path }));
            },
        },
    ],
    resolve: {
        alias: {
            // This Rollup aliases are extracted from @esbuild-plugins/node-modules-polyfill,
            // see https://github.com/remorses/esbuild-plugins/blob/master/node-modules-polyfill/src/polyfills.ts
            // process and buffer are excluded because already managed
            // by node-globals-polyfill
            util: "util",
            sys: "util",
            events: "rollup-plugin-node-polyfills/polyfills/events",
            stream: "rollup-plugin-node-polyfills/polyfills/stream",
            path: "rollup-plugin-node-polyfills/polyfills/path",
            querystring: "rollup-plugin-node-polyfills/polyfills/qs",
            punycode: "rollup-plugin-node-polyfills/polyfills/punycode",
            url: "rollup-plugin-node-polyfills/polyfills/url",
            string_decoder: "rollup-plugin-node-polyfills/polyfills/string-decoder",
            http: "rollup-plugin-node-polyfills/polyfills/http",
            https: "rollup-plugin-node-polyfills/polyfills/http",
            os: "rollup-plugin-node-polyfills/polyfills/os",
            assert: "rollup-plugin-node-polyfills/polyfills/assert",
            constants: "rollup-plugin-node-polyfills/polyfills/constants",
            _stream_duplex: "rollup-plugin-node-polyfills/polyfills/readable-stream/duplex",
            _stream_passthrough: "rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough",
            _stream_readable: "rollup-plugin-node-polyfills/polyfills/readable-stream/readable",
            _stream_writable: "rollup-plugin-node-polyfills/polyfills/readable-stream/writable",
            _stream_transform: "rollup-plugin-node-polyfills/polyfills/readable-stream/transform",
            timers: "rollup-plugin-node-polyfills/polyfills/timers",
            console: "rollup-plugin-node-polyfills/polyfills/console",
            vm: "rollup-plugin-node-polyfills/polyfills/vm",
            zlib: "rollup-plugin-node-polyfills/polyfills/zlib",
            tty: "rollup-plugin-node-polyfills/polyfills/tty",
            domain: "rollup-plugin-node-polyfills/polyfills/domain",
        },
    },
    optimizeDeps: {
        esbuildOptions: {
            // Node.js global to browser globalThis
            define: {
                global: "globalThis",
            },
            // Enable esbuild polyfill plugins
            plugins: [
                NodeGlobalsPolyfillPlugin({
                    process: true,
                    buffer: true,
                }),
                NodeModulesPolyfillPlugin(),
            ],
        },
    },
    build: {
        rollupOptions: {
            plugins: [
                // Enable rollup polyfills plugin
                // used during production bundling
                rollupNodePolyFill(),
            ],
        },
    },
};

This configuration has gotten me very close. However, I have odic-client-ts as a dep and I'm getting the following error. Any idea on how to fix this?

Failed to load url rollup-plugin-node-polyfills/polyfills/constants/odic-config (resolved id: rollup-plugin-node-polyfills/polyfills/constants/odic-config). Does the file exist?

@marekmis
Copy link

Had the same problem in Nuxt3 after upgrading to 3.1.1
I was already using polyfills:

import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'

but after upgrading Nuxt (which comes with Vite update) I got error:
✘ [ERROR] The injected path "/Users/../node_modules/@esbuild-plugins/node-globals-polyfill/_virtual-process-polyfill_.js" cannot be resolved

Everything is back in the right order after upgrading dev dependencies to:

    "@esbuild-plugins/node-globals-polyfill": "^0.2.3",
    "@esbuild-plugins/node-modules-polyfill": "^0.2.2",

Thanks @Terkea 👍

@Terkea
Copy link

Terkea commented Jan 27, 2023

try installing the standalone module and replacing it in the vite.config.js
that's how I got around the util issue which is the same

@caioregatieri
Copy link

import rollupNodePolyFill from "rollup-plugin-node-polyfills";

`build: {
outDir: resolve(devPath, 'renderer'),

rollupOptions: {
plugins: [
  injectProcessEnvPlugin({
    NODE_ENV: 'production',
    platform: process.platform,
  }),
  rollupNodePolyFill(),
],
...

},
},`

rollupNodePolyFill doesn't work here, I'm using electron-vite^1.0.12

I got an error by ts:

Type '{ name: string; resolveId(importee: string, importer: string): { id: any; moduleSideEffects: boolean; } | null; load(id: string): string | undefined; transform(code: string, id: string): any; }' is not assignable to type 'false | Plugin | null | undefined'. Type '{ name: string; resolveId(importee: string, importer: string): { id: any; moduleSideEffects: boolean; } | null; load(id: string): string | undefined; transform(code: string, id: string): any; }' is not assignable to type 'Plugin'. Types of property 'resolveId' are incompatible. Type '(importee: string, importer: string) => { id: any; moduleSideEffects: boolean; } | null' is not assignable to type 'ObjectHook<(this: PluginContext, source: string, importer: string | undefined, options: { custom?: CustomPluginOptions | undefined; isEntry: boolean; }) => ResolveIdResult | Promise<...>, {}> | undefined'. Type '(importee: string, importer: string) => { id: any; moduleSideEffects: boolean; } | null' is not assignable to type '(this: PluginContext, source: string, importer: string | undefined, options: { custom?: CustomPluginOptions | undefined; isEntry: boolean; }) => ResolveIdResult | Promise<...>'. Types of parameters 'importer' and 'importer' are incompatible. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2322)

Can someone help me?

@6abotage
Copy link

import rollupNodePolyFill from "rollup-plugin-node-polyfills";

`build: { outDir: resolve(devPath, 'renderer'),

rollupOptions: {
plugins: [
  injectProcessEnvPlugin({
    NODE_ENV: 'production',
    platform: process.platform,
  }),
  rollupNodePolyFill(),
],
...

}, },`

rollupNodePolyFill doesn't work here, I'm using electron-vite^1.0.12

I got an error by ts:

Type '{ name: string; resolveId(importee: string, importer: string): { id: any; moduleSideEffects: boolean; } | null; load(id: string): string | undefined; transform(code: string, id: string): any; }' is not assignable to type 'false | Plugin | null | undefined'. Type '{ name: string; resolveId(importee: string, importer: string): { id: any; moduleSideEffects: boolean; } | null; load(id: string): string | undefined; transform(code: string, id: string): any; }' is not assignable to type 'Plugin'. Types of property 'resolveId' are incompatible. Type '(importee: string, importer: string) => { id: any; moduleSideEffects: boolean; } | null' is not assignable to type 'ObjectHook<(this: PluginContext, source: string, importer: string | undefined, options: { custom?: CustomPluginOptions | undefined; isEntry: boolean; }) => ResolveIdResult | Promise<...>, {}> | undefined'. Type '(importee: string, importer: string) => { id: any; moduleSideEffects: boolean; } | null' is not assignable to type '(this: PluginContext, source: string, importer: string | undefined, options: { custom?: CustomPluginOptions | undefined; isEntry: boolean; }) => ResolveIdResult | Promise<...>'. Types of parameters 'importer' and 'importer' are incompatible. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2322)

Can someone help me?

CodeSandbox?

@caioregatieri
Copy link

I solve it with:

electron.vite.config.ts
`
build: {
outDir: resolve(devPath, 'renderer'),

  rollupOptions: {
    plugins: [
      injectProcessEnvPlugin({
        NODE_ENV: 'production',
        platform: process.platform,
      }),
      rollupNodePolyFill,
    ],
  },
},

`
and this:

index.html
<script> global = globalThis; </script>

@xiangnanscu
Copy link

rollup-plugin-node-polyfills

@Terkea Hello, I use yours and get this error:

Error: Build failed with 2 errors:
error: Could not read from file: /root/zzb/node_modules/@esbuild-plugins/node-globals-polyfill/_virtual-process-polyfill_.js
error: Could not read from file: /root/zzb/node_modules/@esbuild-plugins/node-globals-polyfill/_virtual-buffer-polyfill_.js
    at failureErrorWithLog (/root/zzb/node_modules/esbuild/lib/main.js:1566:15)
    at /root/zzb/node_modules/esbuild/lib/main.js:1024:28
    at runOnEndCallbacks (/root/zzb/node_modules/esbuild/lib/main.js:1438:61)
    at buildResponseToResult (/root/zzb/node_modules/esbuild/lib/main.js:1022:7)
    at /root/zzb/node_modules/esbuild/lib/main.js:1134:14
    at responseCallbacks.<computed> (/root/zzb/node_modules/esbuild/lib/main.js:671:9)
    at handleIncomingPacket (/root/zzb/node_modules/esbuild/lib/main.js:726:9)
    at Socket.readFromStdout (/root/zzb/node_modules/esbuild/lib/main.js:647:7)
    at Socket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:324:12)
    at readableAddChunk (node:internal/streams/readable:297:9)
    at Readable.push (node:internal/streams/readable:234:10)
    at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)

@dennisharrison
Copy link

rollup-plugin-node-polyfills

@Terkea Hello, I use yours and get this error:

Error: Build failed with 2 errors:
error: Could not read from file: /root/zzb/node_modules/@esbuild-plugins/node-globals-polyfill/_virtual-process-polyfill_.js
error: Could not read from file: /root/zzb/node_modules/@esbuild-plugins/node-globals-polyfill/_virtual-buffer-polyfill_.js
    at failureErrorWithLog (/root/zzb/node_modules/esbuild/lib/main.js:1566:15)
    at /root/zzb/node_modules/esbuild/lib/main.js:1024:28
    at runOnEndCallbacks (/root/zzb/node_modules/esbuild/lib/main.js:1438:61)
    at buildResponseToResult (/root/zzb/node_modules/esbuild/lib/main.js:1022:7)
    at /root/zzb/node_modules/esbuild/lib/main.js:1134:14
    at responseCallbacks.<computed> (/root/zzb/node_modules/esbuild/lib/main.js:671:9)
    at handleIncomingPacket (/root/zzb/node_modules/esbuild/lib/main.js:726:9)
    at Socket.readFromStdout (/root/zzb/node_modules/esbuild/lib/main.js:647:7)
    at Socket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:324:12)
    at readableAddChunk (node:internal/streams/readable:297:9)
    at Readable.push (node:internal/streams/readable:234:10)
    at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)

Update to Vite 4.2 solved the issue for me.

@rebz
Copy link

rebz commented May 5, 2023

Have a project with a WebRTC video player component and we are receiving the following error:

this.once is not a function

Seems to be an issue with how Vite handles transforms around Duplex.once and _readable_stream.

Here is a GitHub thread where someone was discussing a similar issue:
nodejs/readable-stream#315 (comment)

Has anyone ran into this or have a solution for it?
I've tried a variety of solutions in this thread and other GitHub threads... none have worked so far. I am on the latest version of Vite ("vite": "^4.3.4",).

@txreplay
Copy link

Anyone know how to handle cytpo ? It seems to work in build mode but can't get it to work in dev with crypto-browserify

@minorvargas-hoag
Copy link

this worked. thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment