vite-plugin-node-polyfills
A Vite plugin to polyfill Node's Core Modules for browser environments. Supports node:
protocol imports.
Why do I need this?
Module "stream" has been externalized for browser compatibility. Cannot access "stream.Readable" in client code.
Since browsers do not support Node's Core Modules, packages that use them must be polyfilled to function in browser environments. In an attempt to prevent runtime errors, Vite produces errors or warnings when your code references builtin modules such as fs
or path
.
Getting Started
Install the package as a dev dependency.
npm install --save-dev vite-plugin-node-polyfills
pnpm install --save-dev vite-plugin-node-polyfills
yarn add --dev vite-plugin-node-polyfills
Add the plugin to your vite.config.ts
file.
import { defineConfig } from 'vite'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
export default defineConfig({
plugins: [
nodePolyfills(),
],
})
Customizable when you need it
The following options are available to customize it for your needs.
import { defineConfig } from 'vite'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
export default defineConfig({
plugins: [
nodePolyfills({
include: ['path'],
exclude: [
'http',
],
globals: {
Buffer: true,
global: true,
process: true,
},
overrides: {
fs: 'memfs',
},
protocolImports: true,
}),
],
})
All polyfills
- If protocolImports is true, also adds node:[module]
[
'_stream_duplex',
'_stream_passthrough',
'_stream_readable',
'_stream_transform',
'_stream_writable',
'assert',
'buffer',
'child_process',
'cluster',
'console',
'constants',
'crypto',
'dgram',
'dns',
'domain',
'events',
'fs',
'http',
'http2',
'https',
'module',
'net',
'os',
'path',
'process',
'punycode',
'querystring',
'readline',
'repl',
'stream',
'string_decoder',
'sys',
'timers',
'timers/promises',
'tls',
'tty',
'url',
'util',
'vm',
'zlib',
]