@@ -5,14 +5,34 @@ import { handleCircularDependancyWarning } from 'node-stdlib-browser/helpers/rol
5
5
import esbuildPlugin from 'node-stdlib-browser/helpers/esbuild/plugin'
6
6
import type { Plugin } from 'vite'
7
7
8
+ export type ModuleName = keyof typeof stdLibBrowser
9
+ export type ModuleNameWithoutNodePrefix < T = ModuleName > = T extends `node:${infer P } ` ? P : never
10
+
8
11
interface PolyfillOptions {
9
- protocolImports : boolean
12
+ /**
13
+ * @example
14
+ *
15
+ * ```ts
16
+ * nodePolyfills({
17
+ * exclude: ['fs', 'path']
18
+ * })
19
+ * ```
20
+ */
21
+ exclude : ModuleNameWithoutNodePrefix [ ] ,
22
+ /**
23
+ * @default true
24
+ */
25
+ protocolImports : boolean ,
26
+ }
27
+
28
+ const isProtocolImport = ( name : string ) => {
29
+ return name . startsWith ( 'node:' )
10
30
}
11
31
12
32
/**
13
33
* Returns a Vite plugin to polyfill Node's Core Modules for browser environments. Supports `node:` protocol imports.
14
34
*
15
- * @example Use it in `vite.config.ts`
35
+ * @example
16
36
*
17
37
* ```ts
18
38
* // vite.config.ts
@@ -22,6 +42,8 @@ interface PolyfillOptions {
22
42
* export default defineConfig({
23
43
* plugins: [
24
44
* nodePolyfills({
45
+ * // Specific modules that should not be polyfilled.
46
+ * exclude: [],
25
47
* // Whether to polyfill `node:` protocol imports.
26
48
* protocolImports: true,
27
49
* }),
@@ -33,27 +55,34 @@ export const nodePolyfills = (options: Partial<PolyfillOptions> = {}): Plugin =>
33
55
const require = createRequire ( import . meta. url )
34
56
const globalShimsPath = require . resolve ( 'node-stdlib-browser/helpers/esbuild/shim' )
35
57
const optionsResolved : PolyfillOptions = {
58
+ exclude : [ ] ,
36
59
protocolImports : true ,
37
60
// User options take priority.
38
61
...options ,
39
62
}
40
63
64
+ const isExcluded = ( name : string ) => {
65
+ return optionsResolved . exclude . some ( ( excludedName ) => {
66
+ return name === excludedName || name === `node:${ excludedName } `
67
+ } )
68
+ }
69
+
41
70
return {
42
71
name : 'vite-plugin-node-polyfills' ,
43
72
config : ( _config , _env ) => {
44
- const polyfills = Object . entries ( stdLibBrowser ) . reduce ( ( included : Record < string , string > , [ name , value ] ) => {
73
+ const polyfills = ( Object . entries ( stdLibBrowser ) as Array < [ ModuleName , string ] > ) . reduce < Record < ModuleName , string > > ( ( included , [ name , value ] ) => {
45
74
if ( ! optionsResolved . protocolImports ) {
46
- const isProtocolImport = / ^ n o d e : / . test ( name )
47
-
48
- if ( isProtocolImport ) {
75
+ if ( isProtocolImport ( name ) ) {
49
76
return included
50
77
}
51
78
}
52
79
53
- included [ name ] = value
80
+ if ( ! isExcluded ( name ) ) {
81
+ included [ name ] = value
82
+ }
54
83
55
84
return included
56
- } , { } )
85
+ } , { } as Record < ModuleName , string > )
57
86
58
87
return {
59
88
build : {
0 commit comments