A Vite plugin to polyfill Node's Core Modules for browser environments.
npx @tessl/cli install tessl/npm-vite-plugin-node-polyfills@0.24.00
# Vite Plugin Node Polyfills
1
2
A Vite plugin to polyfill Node's Core Modules for browser environments. This plugin enables Node.js packages to run in browsers by providing polyfills for all Node.js built-in modules, with support for the modern `node:` protocol imports and flexible configuration options.
3
4
## Package Information
5
6
- **Package Name**: vite-plugin-node-polyfills
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install --save-dev vite-plugin-node-polyfills`
10
11
## Core Imports
12
13
```typescript
14
import { nodePolyfills } from "vite-plugin-node-polyfills";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { nodePolyfills } = require("vite-plugin-node-polyfills");
21
```
22
23
For shims (when using specific polyfills directly):
24
25
```typescript
26
import "vite-plugin-node-polyfills/shims/buffer";
27
import "vite-plugin-node-polyfills/shims/global";
28
import "vite-plugin-node-polyfills/shims/process";
29
```
30
31
## Basic Usage
32
33
```typescript
34
import { defineConfig } from "vite";
35
import { nodePolyfills } from "vite-plugin-node-polyfills";
36
37
export default defineConfig({
38
plugins: [
39
nodePolyfills(),
40
],
41
});
42
```
43
44
With configuration:
45
46
```typescript
47
import { defineConfig } from "vite";
48
import { nodePolyfills } from "vite-plugin-node-polyfills";
49
50
export default defineConfig({
51
plugins: [
52
nodePolyfills({
53
// Include specific modules only
54
include: ["path", "fs"],
55
// Exclude specific modules
56
exclude: ["http"],
57
// Configure global polyfills
58
globals: {
59
Buffer: true,
60
global: "dev", // Only in development
61
process: false, // Disable process polyfill
62
},
63
// Override default polyfills
64
overrides: {
65
fs: "memfs", // Use memfs instead of default fs polyfill
66
},
67
// Enable node: protocol polyfills
68
protocolImports: true,
69
}),
70
],
71
});
72
```
73
74
## Architecture
75
76
The plugin works by:
77
78
1. **Module Resolution**: Intercepts imports of Node.js core modules and redirects them to browser-compatible polyfills
79
2. **Global Injection**: Optionally injects global variables (Buffer, global, process) into the browser environment
80
3. **Protocol Support**: Handles both traditional imports (`import "fs"`) and modern protocol imports (`import "node:fs"`)
81
4. **Build Integration**: Configures Vite's build pipeline to include polyfills and handle circular dependencies
82
5. **Development Support**: Provides banner injection for isolated scripts (like Vue SFCs) in development mode
83
84
## Capabilities
85
86
### Main Plugin Function
87
88
Creates a Vite plugin instance with Node.js polyfill support.
89
90
```typescript { .api }
91
/**
92
* Returns a Vite plugin to polyfill Node's Core Modules for browser environments.
93
* Supports node: protocol imports and provides flexible configuration options.
94
* @param options - Configuration options for the plugin
95
* @returns Vite Plugin object
96
*/
97
function nodePolyfills(options?: PolyfillOptions): Plugin;
98
99
interface PolyfillOptions {
100
/** Specific modules to include. If empty, includes all modules */
101
include?: ModuleNameWithoutNodePrefix[];
102
/** Specific modules to exclude from polyfilling */
103
exclude?: ModuleNameWithoutNodePrefix[];
104
/** Configuration for global polyfills */
105
globals?: {
106
Buffer?: BooleanOrBuildTarget;
107
global?: BooleanOrBuildTarget;
108
process?: BooleanOrBuildTarget;
109
};
110
/** Alternative modules to use in place of default polyfills */
111
overrides?: { [Key in ModuleNameWithoutNodePrefix]?: string };
112
/** Whether the Node protocol version should be polyfilled too (default: true) */
113
protocolImports?: boolean;
114
}
115
116
type BooleanOrBuildTarget = boolean | BuildTarget;
117
type BuildTarget = "build" | "dev";
118
type ModuleName = keyof typeof stdLibBrowser;
119
type ModuleNameWithoutNodePrefix<T = ModuleName> = T extends `node:${infer P}` ? P : never;
120
```
121
122
**Usage Examples:**
123
124
```typescript
125
// Include only specific polyfills
126
nodePolyfills({
127
include: ["fs", "path", "crypto"],
128
})
129
130
// Exclude specific polyfills
131
nodePolyfills({
132
exclude: ["http", "https", "net"],
133
})
134
135
// Configure globals for different build modes
136
nodePolyfills({
137
globals: {
138
Buffer: "build", // Only in production builds
139
global: true, // Always available
140
process: "dev", // Only in development
141
},
142
})
143
144
// Override default polyfills with custom implementations
145
nodePolyfills({
146
overrides: {
147
fs: "memfs", // Use memfs for filesystem operations
148
crypto: "crypto-js", // Use crypto-js for cryptographic functions
149
},
150
})
151
152
// Disable node: protocol imports
153
nodePolyfills({
154
protocolImports: false,
155
})
156
```
157
158
### Shim Modules
159
160
Direct access to specific polyfills for manual integration.
161
162
```typescript { .api }
163
// Buffer shim exports
164
export {
165
Blob,
166
BlobOptions,
167
Buffer,
168
File,
169
FileOptions,
170
INSPECT_MAX_BYTES,
171
SlowBuffer,
172
TranscodeEncoding,
173
atob,
174
btoa,
175
constants,
176
isAscii,
177
isUtf8,
178
kMaxLength,
179
kStringMaxLength,
180
resolveObjectURL,
181
transcode,
182
} from "vite-plugin-node-polyfills/shims/buffer";
183
184
// Global shim export
185
export { global } from "vite-plugin-node-polyfills/shims/global";
186
187
// Process shim export
188
export { process } from "vite-plugin-node-polyfills/shims/process";
189
```
190
191
**Usage Examples:**
192
193
```typescript
194
// Direct buffer import
195
import { Buffer } from "vite-plugin-node-polyfills/shims/buffer";
196
197
// Direct global import
198
import { global } from "vite-plugin-node-polyfills/shims/global";
199
200
// Direct process import
201
import { process } from "vite-plugin-node-polyfills/shims/process";
202
```
203
204
## Supported Node.js Core Modules
205
206
The plugin provides polyfills for all Node.js core modules:
207
208
**Stream Modules:**
209
- `_stream_duplex`, `_stream_passthrough`, `_stream_readable`, `_stream_transform`, `_stream_writable`
210
211
**Core Modules:**
212
- `assert`, `buffer`, `child_process`, `cluster`, `console`, `constants`, `crypto`
213
- `dgram`, `dns`, `domain`, `events`, `fs`, `http`, `http2`, `https`
214
- `module`, `net`, `os`, `path`, `process`, `punycode`, `querystring`
215
- `readline`, `repl`, `stream`, `string_decoder`, `sys`, `timers`, `timers/promises`
216
- `tls`, `tty`, `url`, `util`, `vm`, `zlib`
217
218
When `protocolImports` is enabled (default), also supports `node:` prefixed imports for all modules (e.g., `node:fs`, `node:path`, `node:crypto`).
219
220
## Types
221
222
```typescript { .api }
223
type BuildTarget = "build" | "dev";
224
225
type BooleanOrBuildTarget = boolean | BuildTarget;
226
227
type ModuleName = keyof typeof stdLibBrowser;
228
229
type ModuleNameWithoutNodePrefix<T = ModuleName> = T extends `node:${infer P}` ? P : never;
230
231
interface PolyfillOptions {
232
include?: ModuleNameWithoutNodePrefix[];
233
exclude?: ModuleNameWithoutNodePrefix[];
234
globals?: {
235
Buffer?: BooleanOrBuildTarget;
236
global?: BooleanOrBuildTarget;
237
process?: BooleanOrBuildTarget;
238
};
239
overrides?: { [Key in ModuleNameWithoutNodePrefix]?: string };
240
protocolImports?: boolean;
241
}
242
243
interface PolyfillOptionsResolved {
244
include: ModuleNameWithoutNodePrefix[];
245
exclude: ModuleNameWithoutNodePrefix[];
246
globals: {
247
Buffer: BooleanOrBuildTarget;
248
global: BooleanOrBuildTarget;
249
process: BooleanOrBuildTarget;
250
};
251
overrides: { [Key in ModuleNameWithoutNodePrefix]?: string };
252
protocolImports: boolean;
253
}
254
```
255
256
## Error Handling
257
258
The plugin handles common polyfill-related issues:
259
260
- **Circular Dependencies**: Automatically suppresses circular dependency warnings from Node.js polyfills
261
- **Missing Modules**: Gracefully handles cases where polyfills are not available for specific modules
262
- **Build Mode Detection**: Correctly applies different polyfill strategies for development vs production builds
263
- **Protocol Import Resolution**: Properly resolves both traditional and `node:` protocol imports