-
-
Notifications
You must be signed in to change notification settings - Fork 433
/
Copy pathinstances.ts
197 lines (170 loc) · 7.6 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
import * as typescript from 'typescript';
import * as path from 'path';
import * as fs from 'fs';
import chalk, { Chalk } from 'chalk';
import { makeAfterCompile } from './after-compile';
import { getConfigFile, getConfigParseResult } from './config';
import { EOL, dtsDtsxRegex } from './constants';
import { getCompilerOptions, getCompiler } from './compilerSetup';
import { hasOwnProperty, makeError, formatErrors, registerWebpackErrors } from './utils';
import * as logger from './logger';
import { makeServicesHost, makeWatchHost } from './servicesHost';
import { makeWatchRun } from './watch-run';
import {
LoaderOptions,
TSFiles,
TSInstance,
TSInstances,
Webpack,
WebpackError
} from './interfaces';
const instances = <TSInstances> {};
/**
* 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
): { instance?: TSInstance, error?: WebpackError } {
if (hasOwnProperty(instances, loaderOptions.instance)) {
const instance = instances[loaderOptions.instance];
if (instance && instance.watchHost) {
if (instance.changedFilesList) {
instance.watchHost.updateRootFileNames();
}
if (instance.watchOfFilesAndCompilerOptions) {
instance.program = instance.watchOfFilesAndCompilerOptions.getProgram().getProgram();
}
}
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)) };
}
return successfulTypeScriptInstance(
loaderOptions, loader, log, colors,
compiler.compiler!, compiler.compilerCompatible!, compiler.compilerDetailsLogMessage!
);
}
function successfulTypeScriptInstance(
loaderOptions: LoaderOptions,
loader: Webpack,
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 configParseResult = getConfigParseResult(compiler, configFile, configFilePath!);
if (configParseResult.errors.length > 0 && !loaderOptions.happyPackMode) {
const errors = formatErrors(configParseResult.errors, loaderOptions, colors, compiler, { file: configFilePath });
registerWebpackErrors(loader._module.errors, errors);
return { error: makeError(colors.red('error while parsing tsconfig.json'), configFilePath) };
}
const compilerOptions = getCompilerOptions(configParseResult);
const files: TSFiles = {};
const otherFiles: TSFiles = {};
const getCustomTransformers = loaderOptions.getCustomTransformers || Function.prototype;
if (loaderOptions.transpileOnly) {
// quick return for transpiling
// we do need to check for any issues with TS options though
const program = 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();
registerWebpackErrors(
loader._module.errors,
formatErrors(diagnostics, loaderOptions, colors, compiler!, {file: configFilePath || 'tsconfig.json'}));
}
const instance: TSInstance = {
compiler,
compilerOptions,
loaderOptions,
files,
otherFiles,
dependencyGraph: {},
reverseDependencyGraph: {},
transformers: getCustomTransformers(),
colors
};
instances[loaderOptions.instance] = instance;
return { 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 => dtsDtsxRegex.test(fileName)) : configParseResult.fileNames;
filesToLoad.forEach(filePath => {
normalizedFilePath = path.normalize(filePath);
files[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! }`))
};
}
// if allowJs is set then we should accept js(x) files
const scriptRegex = configParseResult.options.allowJs && !loaderOptions.entryFileCannotBeJs
? /\.tsx?$|\.jsx?$/i
: /\.tsx?$/i;
const instance: TSInstance = instances[loaderOptions.instance] = {
compiler,
compilerOptions,
loaderOptions,
files,
otherFiles,
languageService: null,
version: 0,
transformers: getCustomTransformers(),
dependencyGraph: {},
reverseDependencyGraph: {},
modifiedFiles: null,
colors
};
if (compiler.createWatchProgram) {
console.log("Using watch api");
// If there is api available for watch, use it instead of language service
const watchHost = makeWatchHost(scriptRegex, log, loader, instance, loaderOptions.appendTsSuffixTo, loaderOptions.appendTsxSuffixTo);
instance.watchOfFilesAndCompilerOptions = compiler.createWatchProgram(watchHost);
instance.program = instance.watchOfFilesAndCompilerOptions.getProgram().getProgram();
}
else {
const servicesHost = makeServicesHost(scriptRegex, log, loader, instance, loaderOptions.appendTsSuffixTo, loaderOptions.appendTsxSuffixTo);
instance.languageService = compiler.createLanguageService(servicesHost, compiler.createDocumentRegistry());
}
loader._compiler.plugin("after-compile", makeAfterCompile(instance, configFilePath));
loader._compiler.plugin("watch-run", makeWatchRun(instance));
return { instance };
}
export function getEmitOutput(instance: TSInstance, filePath: string) {
if (instance.program) {
const outputFiles: typescript.OutputFile[] = [];
const writeFile = (fileName: string, text: string, writeByteOrderMark: boolean) =>
outputFiles.push({ name: fileName, writeByteOrderMark, text });
const sourceFile = instance.program.getSourceFile(filePath);
instance.program.emit(sourceFile, writeFile, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ false, instance.transformers);
return outputFiles;
}
else {
// Emit Javascript
return instance.languageService!.getEmitOutput(filePath).outputFiles;
}
}