-
-
Notifications
You must be signed in to change notification settings - Fork 429
/
instances.ts
161 lines (135 loc) · 5.91 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
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 } 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)) {
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 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);
const diagnostics = program.getOptionsDiagnostics();
// happypack does not have _module.errors - see https://github.com/TypeStrong/ts-loader/issues/336
if (!loaderOptions.happyPackMode) {
registerWebpackErrors(
loader._module.errors,
formatErrors(diagnostics, loaderOptions, colors, compiler!, {file: configFilePath || 'tsconfig.json'}));
}
const instance = {
compiler,
compilerOptions,
loaderOptions,
files,
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,
languageService: null,
version: 0,
transformers: getCustomTransformers(),
dependencyGraph: {},
reverseDependencyGraph: {},
modifiedFiles: null,
colors
};
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 };
}