-
-
Notifications
You must be signed in to change notification settings - Fork 590
/
index.ts
375 lines (316 loc) · 16.1 KB
/
index.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
import { devServerOptionsType } from "./types";
class ServeCommand {
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
async apply(cli: any): Promise<void> {
const loadDevServerOptions = () => {
// TODO simplify this after drop webpack v4 and webpack-dev-server v3
// eslint-disable-next-line @typescript-eslint/no-var-requires, node/no-extraneous-require
const devServer = require("webpack-dev-server");
const isNewDevServerCLIAPI = typeof devServer.schema !== "undefined";
let options = {};
if (isNewDevServerCLIAPI) {
if (cli.webpack.cli && typeof cli.webpack.cli.getArguments === "function") {
options = cli.webpack.cli.getArguments(devServer.schema);
} else {
options = devServer.cli.getArguments();
}
} else {
// eslint-disable-next-line node/no-extraneous-require
options = require("webpack-dev-server/bin/cli-flags");
}
// Old options format
// { devServer: [{...}, {}...] }
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (options.devServer) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return options.devServer;
}
// New options format
// { flag1: {}, flag2: {} }
return Object.keys(options).map((key) => {
options[key].name = key;
return options[key];
});
};
await cli.makeCommand(
{
name: "serve [entries...]",
alias: ["server", "s"],
description: "Run the webpack dev server.",
usage: "[entries...] [options]",
pkg: "@webpack-cli/serve",
dependencies: ["webpack", "webpack-dev-server"],
},
async () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
cli.webpack = await cli.loadWebpack();
let devServerFlags = [];
try {
devServerFlags = loadDevServerOptions();
} catch (error) {
cli.logger.error(
`You need to install 'webpack-dev-server' for running 'webpack serve'.\n${error}`,
);
process.exit(2);
}
const builtInOptions = cli
.getBuiltInOptions()
.filter((option) => option.name !== "watch");
return [...builtInOptions, ...devServerFlags];
},
async (entries, options) => {
const builtInOptions = cli.getBuiltInOptions();
let devServerFlags = [];
try {
devServerFlags = loadDevServerOptions();
} catch (error) {
// Nothing, to prevent future updates
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const webpackCLIOptions: Record<string, any> = {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const devServerCLIOptions: Record<string, any> = {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const processors: Array<(opts: Record<string, any>) => void> = [];
for (const optionName in options) {
const kebabedOption = cli.utils.toKebabCase(optionName);
// `webpack-dev-server` has own logic for the `--hot` option
const isBuiltInOption =
kebabedOption !== "hot" &&
builtInOptions.find(
(builtInOption) => builtInOption.name === kebabedOption,
);
if (isBuiltInOption) {
webpackCLIOptions[optionName] = options[optionName];
} else {
const needToProcess = devServerFlags.find(
(devServerOption) =>
devServerOption.name === kebabedOption && devServerOption.processor,
);
if (needToProcess) {
processors.push(needToProcess.processor);
}
devServerCLIOptions[optionName] = options[optionName];
}
}
for (const processor of processors) {
processor(devServerCLIOptions);
}
if (entries.length > 0) {
webpackCLIOptions.entry = [...entries, ...(webpackCLIOptions.entry || [])];
}
webpackCLIOptions.argv = {
...options,
env: { WEBPACK_SERVE: true, ...options.env },
};
const compiler = await cli.createCompiler(webpackCLIOptions);
if (!compiler) {
return;
}
const servers = [];
if (cli.needWatchStdin(compiler) || devServerCLIOptions.stdin) {
// TODO remove in the next major release
// Compatibility with old `stdin` option for `webpack-dev-server`
// Should be removed for the next major release on both sides
if (devServerCLIOptions.stdin) {
delete devServerCLIOptions.stdin;
}
process.stdin.on("end", () => {
Promise.all(
servers.map((server) => {
if (typeof server.stop === "function") {
return server.stop();
}
// TODO remove in the next major release
return new Promise<void>((resolve) => {
server.close(() => {
resolve();
});
});
}),
).then(() => {
process.exit(0);
});
});
process.stdin.resume();
}
// eslint-disable-next-line @typescript-eslint/no-var-requires, node/no-extraneous-require
const DevServer = require("webpack-dev-server");
const isNewDevServerCLIAPI = typeof DevServer.schema !== "undefined";
let devServerVersion;
try {
// eslint-disable-next-line node/no-extraneous-require, @typescript-eslint/no-var-requires
devServerVersion = require("webpack-dev-server/package.json").version;
} catch (err) {
cli.logger.error(
`You need to install 'webpack-dev-server' for running 'webpack serve'.\n${err}`,
);
process.exit(2);
}
const compilers =
typeof compiler.compilers !== "undefined" ? compiler.compilers : [compiler];
const possibleCompilers = compilers.filter(
(compiler) => compiler.options.devServer,
);
const compilersForDevServer =
possibleCompilers.length > 0 ? possibleCompilers : [compilers[0]];
const isDevServer4 = devServerVersion.startsWith("4");
const usedPorts = [];
for (const compilerForDevServer of compilersForDevServer) {
let devServerOptions: devServerOptionsType;
if (isNewDevServerCLIAPI) {
const args = devServerFlags.reduce((accumulator, flag) => {
accumulator[flag.name] = flag;
return accumulator;
}, {});
const values = Object.keys(devServerCLIOptions).reduce(
(accumulator, name) => {
const kebabName = cli.utils.toKebabCase(name);
if (args[kebabName]) {
accumulator[kebabName] = options[name];
}
return accumulator;
},
{},
);
const result = { ...(compilerForDevServer.options.devServer || {}) };
const problems = (
cli.webpack.cli &&
typeof cli.webpack.cli.processArguments === "function"
? cli.webpack.cli
: DevServer.cli
).processArguments(args, result, values);
if (problems) {
const groupBy = (xs, key) => {
return xs.reduce((rv, x) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
const problemsByPath = groupBy(problems, "path");
for (const path in problemsByPath) {
const problems = problemsByPath[path];
problems.forEach((problem) => {
cli.logger.error(
`${cli.utils.capitalizeFirstLetter(
problem.type.replace(/-/g, " "),
)}${
problem.value ? ` '${problem.value}'` : ""
} for the '--${problem.argument}' option${
problem.index ? ` by index '${problem.index}'` : ""
}`,
);
if (problem.expected) {
cli.logger.error(`Expected: '${problem.expected}'`);
}
});
}
process.exit(2);
}
devServerOptions = result;
} else {
// TODO remove in the next major release
const mergeOptions = (
devServerOptions: devServerOptionsType,
devServerCliOptions: devServerOptionsType,
): devServerOptionsType => {
// CLI options should take precedence over devServer options,
// and CLI options should have no default values included
const options = { ...devServerOptions, ...devServerCliOptions };
if (devServerOptions.client && devServerCliOptions.client) {
// the user could set some client options in their devServer config,
// then also specify client options on the CLI
options.client = {
...devServerOptions.client,
...devServerCliOptions.client,
};
}
return options;
};
devServerOptions = mergeOptions(
compilerForDevServer.options.devServer || {},
devServerCLIOptions,
);
}
// TODO remove in the next major release
if (!isDevServer4) {
const getPublicPathOption = (): string => {
const normalizePublicPath = (publicPath): string =>
typeof publicPath === "undefined" || publicPath === "auto"
? "/"
: publicPath;
if (options.outputPublicPath) {
return normalizePublicPath(
compilerForDevServer.options.output.publicPath,
);
}
if (devServerOptions.publicPath) {
return normalizePublicPath(devServerOptions.publicPath);
}
return normalizePublicPath(
compilerForDevServer.options.output.publicPath,
);
};
const getStatsOption = (): string | boolean => {
if (options.stats) {
return options.stats;
}
if (devServerOptions.stats) {
return devServerOptions.stats;
}
return compilerForDevServer.options.stats;
};
devServerOptions.host = devServerOptions.host || "localhost";
devServerOptions.port = devServerOptions.port || 8080;
devServerOptions.stats = getStatsOption();
devServerOptions.publicPath = getPublicPathOption();
}
if (devServerOptions.port) {
const portNumber = Number(devServerOptions.port);
if (usedPorts.find((port) => portNumber === port)) {
throw new Error(
"Unique ports must be specified for each devServer option in your webpack configuration. Alternatively, run only 1 devServer config using the --config-name flag to specify your desired config.",
);
}
usedPorts.push(portNumber);
}
try {
let server;
// TODO: remove after dropping webpack-dev-server@v3
if (isDevServer4) {
server = new DevServer(devServerOptions, compiler);
} else {
server = new DevServer(compiler, devServerOptions);
}
if (typeof server.start === "function") {
await server.start();
} else {
// TODO remove in the next major release
server.listen(
devServerOptions.port,
devServerOptions.host,
(error): void => {
if (error) {
throw error;
}
},
);
}
servers.push(server);
} catch (error) {
if (cli.isValidationError(error)) {
cli.logger.error(error.message);
} else {
cli.logger.error(error);
}
process.exit(2);
}
}
},
);
}
}
export default ServeCommand;