@@ -131,14 +131,17 @@ function createWatch(opt: ViteMockOptions) {
131131}
132132
133133// clear cache
134- // function cleanRequireCache(opt: ViteMockOptions) {
135- // const { absConfigPath, absMockPath } = getPath(opt);
136- // Object.keys(require.cache).forEach((file) => {
137- // if (file === absConfigPath || file.indexOf(absMockPath) > -1) {
138- // delete require.cache[file];
139- // }
140- // });
141- // }
134+ function cleanRequireCache ( opt : ViteMockOptions ) {
135+ if ( ! require || ! require . cache ) {
136+ return ;
137+ }
138+ const { absConfigPath, absMockPath } = getPath ( opt ) ;
139+ Object . keys ( require . cache ) . forEach ( ( file ) => {
140+ if ( file === absConfigPath || file . indexOf ( absMockPath ) > - 1 ) {
141+ delete require . cache [ file ] ;
142+ }
143+ } ) ;
144+ }
142145
143146function parseJson ( req : IncomingMessage ) : Promise < Recordable > {
144147 return new Promise ( ( resolve ) => {
@@ -161,7 +164,7 @@ function parseJson(req: IncomingMessage): Promise<Recordable> {
161164
162165// load mock .ts files and watch
163166async function getMockConfig ( opt : ViteMockOptions ) {
164- // cleanRequireCache(opt);
167+ cleanRequireCache ( opt ) ;
165168 const { absConfigPath, absMockPath } = getPath ( opt ) ;
166169 const { ignore, configPath, logger } = opt ;
167170
@@ -254,31 +257,35 @@ function loggerOutput(title: string, msg: string, type: 'info' | 'error' = 'info
254257// Parse file content
255258export async function loadConfigFromBundledFile ( fileName : string , bundledCode : string ) {
256259 const extension = path . extname ( fileName ) ;
260+
257261 // @ts -expect-error
258262 const extensions = module . Module . _extensions ;
259263 let defaultLoader : any ;
260264 const isJs = extension === '.js' ;
261265 if ( isJs ) {
262- defaultLoader = require . extensions [ extension ] ! ;
266+ defaultLoader = extensions [ extension ] ! ;
263267 }
264268
265269 extensions [ extension ] = ( module : NodeModule , filename : string ) => {
266270 if ( filename === fileName ) {
267271 ( module as NodeModuleWithCompile ) . _compile ( bundledCode , filename ) ;
268272 } else {
269- require . extensions [ extension ] ! ( module , filename ) ;
270- defaultLoader ( module , filename ) ;
273+ if ( ! isJs ) {
274+ extensions [ extension ] ! ( module , filename ) ;
275+ } else {
276+ defaultLoader ( module , filename ) ;
277+ }
271278 }
272279 } ;
273280 let config ;
274281 try {
275- if ( isJs ) {
282+ if ( isJs && require && require . cache ) {
276283 delete require . cache [ fileName ] ;
277284 }
278285 const raw = require ( fileName ) ;
279286 config = raw . __esModule ? raw . default : raw ;
280287 if ( defaultLoader && isJs ) {
281- require . extensions [ extension ] = defaultLoader ;
288+ extensions [ extension ] = defaultLoader ;
282289 }
283290 } catch ( error ) {
284291 console . error ( error ) ;
0 commit comments