1+ import { builtinModules } from 'node:module' ;
12import { createMiddleware } from '@hattip/adapter-node' ;
23import { Miniflare } from 'miniflare' ;
34import * as vite from 'vite' ;
@@ -9,6 +10,7 @@ import { getMiniflareOptions } from './miniflare-options';
910import {
1011 getNodeCompatAliases ,
1112 injectGlobalCode ,
13+ isNodeCompat ,
1214 resolveNodeAliases ,
1315} from './node-js-compat' ;
1416import { normalizePluginConfig } from './plugin-config' ;
@@ -66,6 +68,9 @@ export function cloudflare<T extends Record<string, WorkerOptions>>(
6668 pluginConfig ,
6769 resolvedConfig ,
6870 ) ;
71+ Object . keys ( pluginConfig . workers ) . forEach ( ( name ) =>
72+ addNodeBuiltinsIfNeeded ( resolvedConfig , name , normalizedPluginConfig ) ,
73+ ) ;
6974 } ,
7075 resolveId ( source ) {
7176 const worker = normalizedPluginConfig . workers [ this . environment . name ] ;
@@ -147,3 +152,38 @@ export function cloudflare<T extends Record<string, WorkerOptions>>(
147152 } ,
148153 } ;
149154}
155+
156+ /**
157+ * Adds the a worker resolved configuration the necessary node builtin config options is the worker is using under nodejs compat
158+ *
159+ * @param resolvedConfig the vite resolved config (that will be side-effectfully updated)
160+ * @param name the name of the worker
161+ * @param normalizedPluginConfig the normalized/resolved plugin config
162+ */
163+ function addNodeBuiltinsIfNeeded (
164+ resolvedConfig : vite . ResolvedConfig ,
165+ name : string ,
166+ normalizedPluginConfig : NormalizedPluginConfig ,
167+ ) {
168+ invariant (
169+ resolvedConfig . environments [ name ] && normalizedPluginConfig . workers [ name ] ,
170+ `environment configs for worker "${ name } " not found` ,
171+ ) ;
172+
173+ const nodeCompat = isNodeCompat (
174+ normalizedPluginConfig . workers [ name ] . workerOptions ,
175+ ) ;
176+
177+ const nodeCompatModules = nodeCompat
178+ ? [ ...builtinModules . concat ( builtinModules . map ( ( m ) => `node:${ m } ` ) ) ]
179+ : [ ] ;
180+
181+ resolvedConfig . environments [ name ] . resolve . builtins = [
182+ ...resolvedConfig . environments [ name ] . resolve . builtins ,
183+ ...nodeCompatModules ,
184+ ] ;
185+ resolvedConfig . environments [ name ] . optimizeDeps . exclude = [
186+ ...( resolvedConfig . environments [ name ] . optimizeDeps . exclude ?? [ ] ) ,
187+ ...nodeCompatModules ,
188+ ] ;
189+ }
0 commit comments