-
-
Notifications
You must be signed in to change notification settings - Fork 429
/
instances.ts
350 lines (314 loc) · 10.2 KB
/
instances.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import chalk, { Chalk } from 'chalk';
import * as fs from 'fs';
import * as path from 'path';
import * as typescript from 'typescript';
import * as webpack from 'webpack';
import { makeAfterCompile } from './after-compile';
import { getCompiler, getCompilerOptions } from './compilerSetup';
import { getConfigFile, getConfigParseResult } from './config';
import { dtsDtsxOrDtsDtsxMapRegex, EOL } from './constants';
import {
LoaderOptions,
TSFile,
TSFiles,
TSInstance,
TSInstances,
WebpackError
} from './interfaces';
import * as logger from './logger';
import { makeServicesHost, makeWatchHost } from './servicesHost';
import {
appendSuffixesIfMatch,
ensureProgram,
formatErrors,
isUsingProjectReferences,
makeError
} from './utils';
import { makeWatchRun } from './watch-run';
const instances = {} as TSInstances;
// TODO: workaround for issues with webpack typings
type PatchedHookCallback = any;
/**
* The loader is executed once for each file seen by webpack. However, we need to keep
* a persistent instance of TypeScript that contains all of the files in the program
* along with definition files and options. This function either creates an instance
* or returns the existing one. Multiple instances are possible by using the
* `instance` property.
*/
export function getTypeScriptInstance(
loaderOptions: LoaderOptions,
loader: webpack.loader.LoaderContext
): { instance?: TSInstance; error?: WebpackError } {
if (instances.hasOwnProperty(loaderOptions.instance)) {
const instance = instances[loaderOptions.instance];
ensureProgram(instance);
return { instance: instances[loaderOptions.instance] };
}
const colors = new chalk.constructor({ enabled: loaderOptions.colors });
const log = logger.makeLogger(loaderOptions, colors);
const compiler = getCompiler(loaderOptions, log);
if (compiler.errorMessage !== undefined) {
return { error: makeError(colors.red(compiler.errorMessage), undefined) };
}
return successfulTypeScriptInstance(
loaderOptions,
loader,
log,
colors,
compiler.compiler!,
compiler.compilerCompatible!,
compiler.compilerDetailsLogMessage!
);
}
function successfulTypeScriptInstance(
loaderOptions: LoaderOptions,
loader: webpack.loader.LoaderContext,
log: logger.Logger,
colors: Chalk,
compiler: typeof typescript,
compilerCompatible: boolean,
compilerDetailsLogMessage: string
) {
const configFileAndPath = getConfigFile(
compiler,
colors,
loader,
loaderOptions,
compilerCompatible,
log,
compilerDetailsLogMessage!
);
if (configFileAndPath.configFileError !== undefined) {
const { message, file } = configFileAndPath.configFileError;
return {
error: makeError(
colors.red('error while reading tsconfig.json:' + EOL + message),
file
)
};
}
const { configFilePath, configFile } = configFileAndPath;
const basePath = loaderOptions.context || path.dirname(configFilePath || '');
const configParseResult = getConfigParseResult(
compiler,
configFile,
basePath
);
if (configParseResult.errors.length > 0 && !loaderOptions.happyPackMode) {
const errors = formatErrors(
configParseResult.errors,
loaderOptions,
colors,
compiler,
{ file: configFilePath },
loader.context
);
loader._module.errors.push(...errors);
return {
error: makeError(
colors.red('error while parsing tsconfig.json'),
configFilePath
)
};
}
const compilerOptions = getCompilerOptions(configParseResult);
const files: TSFiles = new Map<string, TSFile>();
const otherFiles: TSFiles = new Map<string, TSFile>();
const appendTsTsxSuffixesIfRequired =
loaderOptions.appendTsSuffixTo.length > 0 ||
loaderOptions.appendTsxSuffixTo.length > 0
? (filePath: string) =>
appendSuffixesIfMatch(
{
'.ts': loaderOptions.appendTsSuffixTo,
'.tsx': loaderOptions.appendTsxSuffixTo
},
filePath
)
: (filePath: string) => filePath;
// same strategy as https://github.com/s-panferov/awesome-typescript-loader/pull/531/files
let { getCustomTransformers: customerTransformers } = loaderOptions;
let getCustomTransformers = Function.prototype;
if (typeof customerTransformers === 'function') {
getCustomTransformers = customerTransformers;
} else if (typeof customerTransformers === 'string') {
try {
customerTransformers = require(customerTransformers);
} catch (err) {
throw new Error(
`Failed to load customTransformers from "${
loaderOptions.getCustomTransformers
}": ${err.message}`
);
}
if (typeof customerTransformers !== 'function') {
throw new Error(
`Custom transformers in "${
loaderOptions.getCustomTransformers
}" should export a function, got ${typeof getCustomTransformers}`
);
}
getCustomTransformers = customerTransformers;
}
if (loaderOptions.transpileOnly) {
// quick return for transpiling
// we do need to check for any issues with TS options though
const program =
configParseResult.projectReferences !== undefined
? compiler!.createProgram({
rootNames: configParseResult.fileNames,
options: configParseResult.options,
projectReferences: configParseResult.projectReferences
})
: compiler!.createProgram([], compilerOptions);
// happypack does not have _module.errors - see https://github.com/TypeStrong/ts-loader/issues/336
if (!loaderOptions.happyPackMode) {
const diagnostics = program.getOptionsDiagnostics();
const errors = formatErrors(
diagnostics,
loaderOptions,
colors,
compiler!,
{ file: configFilePath || 'tsconfig.json' },
loader.context
);
loader._module.errors.push(...errors);
}
instances[loaderOptions.instance] = {
compiler,
compilerOptions,
appendTsTsxSuffixesIfRequired,
loaderOptions,
files,
otherFiles,
program,
dependencyGraph: {},
reverseDependencyGraph: {},
transformers: getCustomTransformers(program),
colors
};
return { instance: instances[loaderOptions.instance] };
}
// Load initial files (core lib files, any files specified in tsconfig.json)
let normalizedFilePath: string;
try {
const filesToLoad = loaderOptions.onlyCompileBundledFiles
? configParseResult.fileNames.filter(fileName =>
dtsDtsxOrDtsDtsxMapRegex.test(fileName)
)
: configParseResult.fileNames;
filesToLoad.forEach(filePath => {
normalizedFilePath = path.normalize(filePath);
files.set(normalizedFilePath, {
text: fs.readFileSync(normalizedFilePath, 'utf-8'),
version: 0
});
});
} catch (exc) {
return {
error: makeError(
colors.red(
`A file specified in tsconfig.json could not be found: ${normalizedFilePath!}`
),
normalizedFilePath!
)
};
}
// if allowJs is set then we should accept js(x) files
const scriptRegex =
configParseResult.options.allowJs === true
? /\.tsx?$|\.jsx?$/i
: /\.tsx?$/i;
const instance: TSInstance = (instances[loaderOptions.instance] = {
compiler,
compilerOptions,
appendTsTsxSuffixesIfRequired,
loaderOptions,
files,
otherFiles,
languageService: null,
version: 0,
transformers: {} as typescript.CustomTransformers, // this is only set temporarily, custom transformers are created further down
dependencyGraph: {},
reverseDependencyGraph: {},
modifiedFiles: null,
colors
});
if (!loader._compiler.hooks) {
throw new Error(
"You may be using an old version of webpack; please check you're using at least version 4"
);
}
if (loaderOptions.experimentalWatchApi && compiler.createWatchProgram) {
log.logInfo('Using watch api');
// If there is api available for watch, use it instead of language service
instance.watchHost = makeWatchHost(
scriptRegex,
log,
loader,
instance,
configParseResult.projectReferences
);
instance.watchOfFilesAndCompilerOptions = compiler.createWatchProgram(
instance.watchHost
);
instance.program = instance.watchOfFilesAndCompilerOptions
.getProgram()
.getProgram();
instance.transformers = getCustomTransformers(instance.program);
} else {
const servicesHost = makeServicesHost(
scriptRegex,
log,
loader,
instance,
loaderOptions.experimentalFileCaching,
configParseResult.projectReferences
);
instance.languageService = compiler.createLanguageService(
servicesHost.servicesHost,
compiler.createDocumentRegistry()
);
if (servicesHost.clearCache !== null) {
loader._compiler.hooks.watchRun.tap('ts-loader', servicesHost.clearCache);
}
instance.transformers = getCustomTransformers(
instance.languageService!.getProgram()
);
}
loader._compiler.hooks.afterCompile.tapAsync('ts-loader', makeAfterCompile(
instance,
configFilePath
) as PatchedHookCallback);
loader._compiler.hooks.watchRun.tapAsync('ts-loader', makeWatchRun(instance));
return { instance };
}
export function getEmitOutput(instance: TSInstance, filePath: string) {
const program = ensureProgram(instance);
if (program !== undefined) {
const outputFiles: typescript.OutputFile[] = [];
const writeFile = (
fileName: string,
text: string,
writeByteOrderMark: boolean
) => outputFiles.push({ name: fileName, writeByteOrderMark, text });
const sourceFile = program.getSourceFile(filePath);
// The source file will be undefined if it’s part of an unbuilt project reference
if (sourceFile !== undefined || !isUsingProjectReferences(instance)) {
program.emit(
sourceFile,
writeFile,
/*cancellationToken*/ undefined,
/*emitOnlyDtsFiles*/ false,
instance.transformers
);
}
return outputFiles;
} else {
// Emit Javascript
return instance.languageService!.getProgram()!.getSourceFile(filePath) ===
undefined
? []
: instance.languageService!.getEmitOutput(filePath).outputFiles;
}
}