@@ -336,21 +336,33 @@ const addAssetHooks = !!webpack.version!.match(/^4.*/)
336
336
makeAfterCompile ( instance , false , true , instance . configFilePath )
337
337
) ;
338
338
339
- // Emit the assets at the afterProcessAssets stage
340
- loader . _compilation . hooks . afterProcessAssets . tap (
341
- 'ts-loader' ,
342
- ( _ : any ) => {
343
- makeAfterCompile (
344
- instance ,
345
- true ,
346
- false ,
347
- instance . configFilePath
348
- ) ( loader . _compilation , ( ) => {
349
- return null ;
350
- } ) ;
351
- }
339
+ // makeAfterCompile is a closure. It returns a function which closes over the variable checkAllFilesForErrors
340
+ // We need to get the function once and then reuse it, otherwise it will be recreated each time
341
+ // and all files will always be checked.
342
+ const cachedMakeAfterCompile = makeAfterCompile (
343
+ instance ,
344
+ true ,
345
+ false ,
346
+ instance . configFilePath
352
347
) ;
353
348
349
+ // compilation is actually of type webpack.compilation.Compilation, but afterProcessAssets
350
+ // only exists in webpack5 and at the time of writing ts-loader is built using webpack4
351
+ const makeAssetsCallback = ( compilation : any ) => {
352
+ compilation . hooks . afterProcessAssets . tap ( 'ts-loader' , ( ) =>
353
+ cachedMakeAfterCompile ( compilation , ( ) => {
354
+ return null ;
355
+ } )
356
+ ) ;
357
+ } ;
358
+
359
+ // We need to add the hook above for each run.
360
+ // For the first run, we just need to add the hook to loader._compilation
361
+ makeAssetsCallback ( loader . _compilation ) ;
362
+
363
+ // For future calls in watch mode we need to watch for a new compilation and add the hook
364
+ loader . _compiler . hooks . compilation . tap ( 'ts-loader' , makeAssetsCallback ) ;
365
+
354
366
// It may be better to add assets at the processAssets stage (https://webpack.js.org/api/compilation-hooks/#processassets)
355
367
// This requires Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, which does not exist in webpack4
356
368
// Consider changing this when ts-loader is built using webpack5
0 commit comments