@@ -104,6 +104,10 @@ const globalShimBanners = {
104104 ] ,
105105}
106106
107+ const isModuleName = ( name : string ) : name is ModuleName => {
108+ return name in stdLibBrowser
109+ }
110+
107111/**
108112 * Returns a Vite plugin to polyfill Node's Core Modules for browser environments. Supports `node:` protocol imports.
109113 *
@@ -194,6 +198,27 @@ export const nodePolyfills = (options: PolyfillOptions = {}): Plugin[] => {
194198 ...( ( isEnabled ( optionsResolved . globals . process , 'dev' ) ) ? [ require . resolve ( 'vite-plugin-node-polyfills/shims/process' ) ] : [ ] ) ,
195199 ]
196200
201+ const resolvePlugin : Plugin = {
202+ name : 'vite-plugin-node-polyfills:resolve' ,
203+ enforce : 'pre' ,
204+ resolveId : {
205+ // @ts -expect-error -- hook filters are only supported in Vite 6.3.0+
206+ filter : { id : new RegExp ( Object . keys ( stdLibBrowser ) . map ( ( name ) => `^${ name } \/?$` ) . join ( '|' ) ) } ,
207+ async handler ( source , importer , opts ) {
208+ if ( ! optionsResolved . protocolImports && isNodeProtocolImport ( source ) ) {
209+ return
210+ }
211+ source = source . endsWith ( '/' ) ? source . slice ( 0 , - 1 ) : source // strip trailing slash
212+ if ( ! isModuleName ( source ) || isExcluded ( source ) ) {
213+ return
214+ }
215+ const aliased = toOverride ( withoutNodeProtocol ( source ) ) || stdLibBrowser [ source ]
216+ const resolved = await this . resolve ( aliased , importer , { skipSelf : true , ...opts } )
217+ return resolved
218+ } ,
219+ } ,
220+ }
221+
197222 const globalShimsBanner = [
198223 ...( ( isEnabled ( optionsResolved . globals . Buffer , 'dev' ) ) ? globalShimBanners . buffer : [ ] ) ,
199224 ...( ( isEnabled ( optionsResolved . globals . global , 'dev' ) ) ? globalShimBanners . global : [ ] ) ,
@@ -273,16 +298,11 @@ export const nodePolyfills = (options: PolyfillOptions = {}): Plugin[] => {
273298 ...isRolldownVite
274299 ? {
275300 rolldownOptions : {
276- resolve : {
277- // https://github.com/niksy/node-stdlib-browser/blob/3e7cd7f3d115ac5c4593b550e7d8c4a82a0d4ac4/README.md?plain=1#L150
278- alias : {
279- ...polyfills ,
280- } ,
281- } ,
282301 transform : {
283302 define : defines ,
284303 } ,
285304 plugins : [
305+ resolvePlugin ,
286306 {
287307 name : 'vite-plugin-node-polyfills:optimizer' ,
288308 banner : isDev ? globalShimsBanner : undefined ,
@@ -322,16 +342,11 @@ export const nodePolyfills = (options: PolyfillOptions = {}): Plugin[] => {
322342 } ,
323343 } ,
324344 } ,
325- resolve : {
326- // https://github.com/niksy/node-stdlib-browser/blob/3e7cd7f3d115ac5c4593b550e7d8c4a82a0d4ac4/README.md?plain=1#L150
327- alias : {
328- ...polyfills ,
329- } ,
330- } ,
331345 }
332346 } ,
333347 }
334348 return [
349+ resolvePlugin ,
335350 injectPlugin ,
336351 plugin ,
337352 ]
0 commit comments