-
Notifications
You must be signed in to change notification settings - Fork 51
/
plugin.ts
395 lines (348 loc) · 11.2 KB
/
plugin.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
import chalk from "chalk";
import * as TsconfigPaths from "tsconfig-paths";
import * as path from "path";
import * as Options from "./options";
import * as Logger from "./logger";
import { Stats } from "fs";
interface ResolverPlugin {
readonly apply: (resolver: Resolver) => void;
}
interface Resolver {
readonly apply: (plugin: ResolverPlugin) => void;
readonly plugin: (source: string, cb: ResolverCallbackLegacy) => void;
readonly doResolve: doResolveLegacy | doResolve;
readonly join: (relativePath: string, innerRequest: Request) => Request;
readonly fileSystem: ResolverFileSystem;
readonly getHook: (hook: string) => Tapable;
}
type doResolveLegacy = (
target: string,
req: Request,
desc: string,
callback: Callback
) => void;
type doResolve = (
hook: Tapable,
req: Request,
message: string,
resolveContext: ResolveContext,
callback: Callback
) => void;
interface ResolverFileSystem {
readonly stat: (
path: string,
callback: (err: Error, stats: Stats) => void
) => void;
readonly readdir: (
path: string,
callback: (err: Error, files: ReadonlyArray<string>) => void
) => void;
readonly readFile: (
path: string,
callback: (err: Error, data: {}) => void
) => void;
readonly readlink: (
path: string,
callback: (err: Error, linkString: string) => void
) => void;
readonly readJson: (
path: string,
callback: (err: Error, json: {}) => void
) => void;
readonly statSync: (path: string) => Stats;
readonly readdirSync: (path: string) => ReadonlyArray<string>;
readonly readFileSync: (path: string) => {};
readonly readlinkSync: (path: string) => string;
readonly readJsonSync: (path: string) => {};
}
interface ResolveContext {
log?: string;
stack?: string;
missing?: string;
}
interface Tapable {
readonly tapAsync: (
options: TapableOptions,
callback: ResolverCallback
) => Promise<void>;
}
interface TapableOptions {
readonly name: string;
}
type ResolverCallbackLegacy = (request: Request, callback: Callback) => void;
type ResolverCallback = (
request: Request,
resolveContext: ResolveContext,
callback: Callback
) => void;
type CreateInnerCallback = (
callback: Callback,
options: Callback,
message?: string,
messageOptional?: string
) => Callback;
type CreateInnerContext = (
options: {
log?: string;
stack?: string;
missing?: string;
},
message?: string,
messageOptional?: string
) => ResolveContext;
type getInnerRequest = (resolver: Resolver, request: Request) => string;
interface Request {
readonly request?: Request | string;
readonly relativePath: string;
readonly path: string;
readonly context: {
readonly issuer: string;
};
}
interface Callback {
(err?: Error, result?: string): void;
log?: string;
stack?: string;
missing?: string;
}
const getInnerRequest: getInnerRequest = require("enhanced-resolve/lib/getInnerRequest");
export class TsconfigPathsPlugin implements ResolverPlugin {
source: string;
target: string;
log: Logger.Logger;
baseUrl: string;
absoluteBaseUrl: string;
extensions: ReadonlyArray<string>;
matchPath: TsconfigPaths.MatchPathAsync;
constructor(rawOptions: Partial<Options.Options> = {}) {
this.source = "described-resolve";
this.target = "resolve";
const options = Options.getOptions(rawOptions);
this.extensions = options.extensions;
const colors = new chalk.constructor({ enabled: options.colors });
this.log = Logger.makeLogger(options, colors);
const context = options.context || process.cwd();
const loadFrom = options.configFile || context;
const loadResult = TsconfigPaths.loadConfig(loadFrom);
if (loadResult.resultType === "failed") {
this.log.logError(`Failed to load tsconfig.json: ${loadResult.message}`);
} else {
this.log.logInfo(
`tsconfig-paths-webpack-plugin: Using config file at ${
loadResult.configFileAbsolutePath
}`
);
this.baseUrl = options.baseUrl || loadResult.baseUrl;
this.absoluteBaseUrl = options.baseUrl
? path.resolve(options.baseUrl)
: loadResult.absoluteBaseUrl;
this.matchPath = TsconfigPaths.createMatchPathAsync(
this.absoluteBaseUrl,
loadResult.paths
);
}
}
apply(resolver: Resolver): void {
const { baseUrl } = this;
if (!baseUrl) {
// Nothing to do if there is no baseUrl
this.log.logWarning(
"tsconfig-paths-webpack-plugin: Found no baseUrl in tsconfig.json, not applying tsconfig-paths-webpack-plugin"
);
return;
}
// The file system only exists when the plugin is in the resolve context. This means it's also properly placed in the resolve.plugins array.
// If not, we should warn the user that this plugin should be placed in resolve.plugins and not the plugins array of the root config for example.
// This should hopefully prevent issues like: https://github.com/dividab/tsconfig-paths-webpack-plugin/issues/9
if (!resolver.fileSystem) {
this.log.logWarning(
"tsconfig-paths-webpack-plugin: No file system found on resolver." +
" Please make sure you've placed the plugin in the correct part of the configuration." +
" This plugin is a resolver plugin and should be placed in the resolve part of the Webpack configuration."
);
return;
}
// getHook will only exist in Webpack 4, if so we should comply to the Webpack 4 plugin system.
if (resolver.getHook && typeof resolver.getHook === "function") {
resolver
.getHook(this.source)
.tapAsync(
{ name: "TsconfigPathsPlugin" },
createPluginCallback(
this.matchPath,
resolver,
this.absoluteBaseUrl,
resolver.getHook(this.target),
this.extensions
)
);
} else {
// This is the legacy (Webpack < 4.0.0) way of using the plugin system.
resolver.plugin(
this.source,
createPluginLegacy(
this.matchPath,
resolver,
this.absoluteBaseUrl,
this.target,
this.extensions
)
);
}
}
}
function createPluginCallback(
matchPath: TsconfigPaths.MatchPathAsync,
resolver: Resolver,
absoluteBaseUrl: string,
hook: Tapable,
extensions: ReadonlyArray<string>
): ResolverCallback {
const fileExistAsync = createFileExistAsync(resolver.fileSystem);
const readJsonAsync = createReadJsonAsync(resolver.fileSystem);
return (
request: Request,
resolveContext: ResolveContext,
callback: Callback
) => {
const innerRequest = getInnerRequest(resolver, request);
if (
!innerRequest ||
(innerRequest.startsWith(".") || innerRequest.startsWith(".."))
) {
return callback();
}
matchPath(
innerRequest,
readJsonAsync,
fileExistAsync,
extensions,
(err, foundMatch) => {
if (err) {
return callback(err);
}
if (!foundMatch) {
return callback();
}
const newRequest = {
...request,
request: foundMatch,
path: absoluteBaseUrl
};
// Only at this point we are sure we are dealing with the latest Webpack version (>= 4.0.0)
// So only now can we require the createInnerContext function.
// (It doesn't exist in legacy versions)
const createInnerContext: CreateInnerContext = require("enhanced-resolve/lib/createInnerContext");
return (resolver.doResolve as doResolve)(
hook,
newRequest,
`Resolved request '${innerRequest}' to '${foundMatch}' using tsconfig.json paths mapping`,
createInnerContext({ ...resolveContext }),
(err2: Error, result2: string): void => {
// Pattern taken from:
// https://github.com/webpack/enhanced-resolve/blob/42ff594140582c3f8f86811f95dea7bf6774a1c8/lib/AliasPlugin.js#L44
if (err2) {
return callback(err2);
}
// Don't allow other aliasing or raw request
if (result2 === undefined) {
return callback(null, null);
}
callback(null, result2);
}
);
}
);
};
}
function createPluginLegacy(
matchPath: TsconfigPaths.MatchPathAsync,
resolver: Resolver,
absoluteBaseUrl: string,
target: string,
extensions: ReadonlyArray<string>
): ResolverCallbackLegacy {
const fileExistAsync = createFileExistAsync(resolver.fileSystem);
const readJsonAsync = createReadJsonAsync(resolver.fileSystem);
return (request, callback) => {
const innerRequest = getInnerRequest(resolver, request);
if (
!innerRequest ||
(innerRequest.startsWith(".") || innerRequest.startsWith(".."))
) {
return callback();
}
matchPath(
innerRequest,
readJsonAsync,
fileExistAsync,
extensions,
(err, foundMatch) => {
if (err) {
return callback(err);
}
if (!foundMatch) {
return callback();
}
const newRequest = {
...request,
request: foundMatch,
path: absoluteBaseUrl
};
// Only at this point we are sure we are dealing with a legacy Webpack version (< 4.0.0)
// So only now can we require the createInnerCallback function.
// (It's already deprecated and might be removed down the line).
const createInnerCallback: CreateInnerCallback = require("enhanced-resolve/lib/createInnerCallback");
return (resolver.doResolve as doResolveLegacy)(
target,
newRequest,
`Resolved request '${innerRequest}' to '${foundMatch}' using tsconfig.json paths mapping`,
createInnerCallback(function(err2: Error, result2: string): void {
// Note:
// *NOT* using an arrow function here because arguments.length implies we have "this"
// That means "this" has to be in the current function scope, and not the scope above.
// Pattern taken from:
// https://github.com/s-panferov/awesome-typescript-loader/blob/10653beff85f555f1f3b5d4bfd7d21513d0e54a4/src/paths-plugin.ts#L169
if (arguments.length > 0) {
return callback(err2, result2);
}
// don't allow other aliasing or raw request
callback(null, null);
}, callback)
);
}
);
};
}
function createReadJsonAsync(
filesystem: ResolverFileSystem
): TsconfigPaths.ReadJsonAsync {
// tslint:disable-next-line:no-any
return (path2: string, callback2: (err?: Error, content?: any) => void) => {
filesystem.readJson(path2, (err, json) => {
// If error assume file does not exist
if (err || !json) {
callback2();
return;
}
callback2(undefined, json);
});
};
}
function createFileExistAsync(
filesystem: ResolverFileSystem
): TsconfigPaths.FileExistsAsync {
return (
path2: string,
callback2: (err?: Error, exists?: boolean) => void
) => {
filesystem.stat(path2, (err: Error, stats: Stats) => {
// If error assume file does not exist
if (err) {
callback2(undefined, false);
return;
}
callback2(undefined, stats ? stats.isFile() : false);
});
};
}