@@ -33,9 +33,22 @@ import {
3333} from './utils' ;
3434import { makeWatchRun } from './watch-run' ;
3535
36- const instances = new Map < string , TSInstance > ( ) ;
36+ // Each TypeScript instance is based on the webpack instance (key of the WeakMap)
37+ // and also the name that was generated or passed via the options (string key of the
38+ // internal Map)
39+ const instanceCache = new WeakMap < webpack . Compiler , Map < string , TSInstance > > ( ) ;
3740const instancesBySolutionBuilderConfigs = new Map < FilePathKey , TSInstance > ( ) ;
3841
42+ function addTSInstanceToCache (
43+ key : webpack . Compiler ,
44+ instanceName : string ,
45+ instance : TSInstance
46+ ) {
47+ const instances = instanceCache . get ( key ) ?? new Map < string , TSInstance > ( ) ;
48+ instances . set ( instanceName , instance ) ;
49+ instanceCache . set ( key , instances ) ;
50+ }
51+
3952/**
4053 * The loader is executed once for each file seen by webpack. However, we need to keep
4154 * a persistent instance of TypeScript that contains all of the files in the program
@@ -47,6 +60,12 @@ export function getTypeScriptInstance(
4760 loaderOptions : LoaderOptions ,
4861 loader : webpack . loader . LoaderContext
4962) : { instance ?: TSInstance ; error ?: WebpackError } {
63+ let instances = instanceCache . get ( loader . _compiler ) ;
64+ if ( ! instances ) {
65+ instances = new Map ( ) ;
66+ instanceCache . set ( loader . _compiler , instances ) ;
67+ }
68+
5069 const existing = instances . get ( loaderOptions . instance ) ;
5170 if ( existing ) {
5271 if ( ! existing . initialSetupPending ) {
@@ -141,7 +160,7 @@ function successfulTypeScriptInstance(
141160 const existing = getExistingSolutionBuilderHost ( configFileKey ) ;
142161 if ( existing ) {
143162 // Reuse the instance if config file for project references is shared.
144- instances . set ( loaderOptions . instance , existing ) ;
163+ addTSInstanceToCache ( loader . _compiler , loaderOptions . instance , existing ) ;
145164 return { instance : existing } ;
146165 }
147166 }
@@ -226,7 +245,12 @@ function successfulTypeScriptInstance(
226245 log,
227246 filePathKeyMapper,
228247 } ;
229- instances . set ( loaderOptions . instance , transpileInstance ) ;
248+
249+ addTSInstanceToCache (
250+ loader . _compiler ,
251+ loaderOptions . instance ,
252+ transpileInstance
253+ ) ;
230254 return { instance : transpileInstance } ;
231255 }
232256
@@ -278,7 +302,8 @@ function successfulTypeScriptInstance(
278302 log,
279303 filePathKeyMapper,
280304 } ;
281- instances . set ( loaderOptions . instance , instance ) ;
305+
306+ addTSInstanceToCache ( loader . _compiler , loaderOptions . instance , instance ) ;
282307 return { instance } ;
283308}
284309
0 commit comments