/
webpack-cli.js
1272 lines (1024 loc) · 46.8 KB
/
webpack-cli.js
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const path = require('path');
const { program } = require('commander');
const getPkg = require('./utils/package-exists');
const webpack = getPkg('webpack') ? require('webpack') : undefined;
const webpackMerge = require('webpack-merge');
const { extensions, jsVariants } = require('interpret');
const rechoir = require('rechoir');
const { createWriteStream, existsSync } = require('fs');
const { distance } = require('fastest-levenshtein');
const { options: coloretteOptions, yellow, cyan, green, bold } = require('colorette');
const { stringifyStream: createJsonStringifyStream } = require('@discoveryjs/json-ext');
const logger = require('./utils/logger');
const { cli, flags } = require('./utils/cli-flags');
const CLIPlugin = require('./plugins/CLIPlugin');
const promptInstallation = require('./utils/prompt-installation');
const toKebabCase = require('./utils/to-kebab-case');
const { resolve, extname } = path;
class WebpackCLI {
constructor() {
this.logger = logger;
// Initialize program
this.program = program;
this.program.name('webpack');
this.program.storeOptionsAsProperties(false);
this.utils = { toKebabCase, getPkg, promptInstallation };
}
async makeCommand(commandOptions, options, action) {
const command = this.program.command(commandOptions.name, {
noHelp: commandOptions.noHelp,
hidden: commandOptions.hidden,
isDefault: commandOptions.isDefault,
});
if (commandOptions.description) {
command.description(commandOptions.description);
}
if (commandOptions.usage) {
command.usage(commandOptions.usage);
}
if (Array.isArray(commandOptions.alias)) {
command.aliases(commandOptions.alias);
} else {
command.alias(commandOptions.alias);
}
if (commandOptions.pkg) {
command.pkg = commandOptions.pkg;
} else {
command.pkg = 'webpack-cli';
}
const { forHelp } = this.program;
let allDependenciesInstalled = true;
if (commandOptions.dependencies && commandOptions.dependencies.length > 0) {
for (const dependency of commandOptions.dependencies) {
const isPkgExist = getPkg(dependency);
if (isPkgExist) {
continue;
} else if (!isPkgExist && forHelp) {
allDependenciesInstalled = false;
continue;
}
try {
await promptInstallation(dependency, () => {
logger.error(
`For using '${green(commandOptions.name)}' command you need to install: '${green(dependency)}' package`,
);
});
} catch (error) {
logger.error("Action Interrupted, use 'webpack-cli help' to see possible commands.");
logger.error(error);
process.exit(2);
}
}
}
if (options) {
if (typeof options === 'function') {
if (forHelp && !allDependenciesInstalled) {
command.description(
`${commandOptions.description} To see all available options you need to install ${commandOptions.dependencies
.map((dependency) => `'${dependency}'`)
.join(',')}.`,
);
options = [];
} else {
options = options();
}
}
options.forEach((optionForCommand) => {
this.makeOption(command, optionForCommand);
});
}
command.action(action);
return command;
}
// TODO refactor this terrible stuff
makeOption(command, option) {
let optionType = option.type;
let isStringOrBool = false;
if (Array.isArray(optionType)) {
// filter out duplicate types
optionType = optionType.filter((type, index) => {
return optionType.indexOf(type) === index;
});
// the only multi type currently supported is String and Boolean,
// if there is a case where a different multi type is needed it
// must be added here
if (optionType.length === 0) {
// if no type is provided in the array fall back to Boolean
optionType = Boolean;
} else if (optionType.length === 1 || optionType.length > 2) {
// treat arrays with 1 or > 2 args as a single type
optionType = optionType[0];
} else {
// only String and Boolean multi type is supported
if (optionType.includes(Boolean) && optionType.includes(String)) {
isStringOrBool = true;
} else {
optionType = optionType[0];
}
}
}
const flags = option.alias ? `-${option.alias}, --${option.name}` : `--${option.name}`;
let flagsWithType = flags;
if (isStringOrBool) {
// commander recognizes [value] as an optional placeholder,
// making this flag work either as a string or a boolean
flagsWithType = `${flags} [value]`;
} else if (optionType !== Boolean) {
// <value> is a required placeholder for any non-Boolean types
flagsWithType = `${flags} <value>`;
}
if (isStringOrBool || optionType === Boolean || optionType === String) {
if (option.multiple) {
// a multiple argument parsing function
const multiArg = (value, previous = []) => previous.concat([value]);
command.option(flagsWithType, option.description, multiArg, option.defaultValue);
} else if (option.multipleType) {
// for options which accept multiple types like env
// so you can do `--env platform=staging --env production`
// { platform: "staging", production: true }
const multiArg = (value, previous = {}) => {
// this ensures we're only splitting by the first `=`
const [allKeys, val] = value.split(/=(.+)/, 2);
const splitKeys = allKeys.split(/\.(?!$)/);
let prevRef = previous;
splitKeys.forEach((someKey, index) => {
if (!prevRef[someKey]) {
prevRef[someKey] = {};
}
if (typeof prevRef[someKey] === 'string') {
prevRef[someKey] = {};
}
if (index === splitKeys.length - 1) {
prevRef[someKey] = val || true;
}
prevRef = prevRef[someKey];
});
return previous;
};
command.option(flagsWithType, option.description, multiArg, option.defaultValue);
} else {
// Prevent default behavior for standalone options
command.option(flagsWithType, option.description, option.defaultValue);
}
} else if (optionType === Number) {
// this will parse the flag as a number
command.option(flagsWithType, option.description, Number, option.defaultValue);
} else {
// in this case the type is a parsing function
command.option(flagsWithType, option.description, optionType, option.defaultValue);
}
if (option.negative) {
// commander requires explicitly adding the negated version of boolean flags
const negatedFlag = `--no-${option.name}`;
command.option(negatedFlag, option.negatedDescription ? option.negatedDescription : `Negative '${option.name}' option.`);
}
}
getBuiltInOptions() {
return flags;
}
async run(args) {
// Built-in internal commands
const bundleCommandOptions = {
name: 'bundle',
alias: 'b',
description: 'Run webpack (default command, can be omitted).',
usage: '[options]',
};
const versionCommandOptions = {
name: 'version',
alias: 'v',
description: "Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and commands.",
usage: '[commands...]',
};
const helpCommandOptions = {
name: 'help',
alias: 'h',
description: 'Display help for commands and options.',
usage: '[command]',
};
// Built-in external commands
const externalBuiltInCommandsInfo = [
{
name: 'serve',
alias: 's',
pkg: '@webpack-cli/serve',
},
{
name: 'info',
alias: 'i',
pkg: '@webpack-cli/info',
},
{
name: 'init',
alias: 'c',
pkg: '@webpack-cli/init',
},
{
name: 'loader',
alias: 'l',
pkg: '@webpack-cli/generators',
},
{
name: 'plugin',
alias: 'p',
pkg: '@webpack-cli/generators',
},
{
name: 'migrate',
alias: 'm',
pkg: '@webpack-cli/migrate',
},
];
const getCommandNameAndOptions = (args) => {
let commandName;
const options = [];
let allowToSearchCommand = true;
args.forEach((arg) => {
if (!arg.startsWith('-') && allowToSearchCommand) {
commandName = arg;
allowToSearchCommand = false;
return;
}
allowToSearchCommand = false;
options.push(arg);
});
const isDefault = typeof commandName === 'undefined';
return { commandName: isDefault ? bundleCommandOptions.name : commandName, options, isDefault };
};
const loadCommandByName = async (commandName, allowToInstall = false) => {
if (commandName === bundleCommandOptions.name || commandName === bundleCommandOptions.alias) {
// Make `bundle|b [options]` command
this.makeCommand(bundleCommandOptions, this.getBuiltInOptions(), async (program) => {
const options = program.opts();
if (typeof colorFromArguments !== 'undefined') {
options.color = colorFromArguments;
}
if (program.args.length > 0) {
const possibleCommands = [].concat([bundleCommandOptions.name]).concat(program.args);
logger.error('Running multiple commands at the same time is not possible');
logger.error(`Found commands: ${possibleCommands.map((item) => `'${item}'`).join(', ')}`);
logger.error("Run 'webpack --help' to see available commands and options");
process.exit(2);
}
await this.bundleCommand(options);
});
} else if (commandName === helpCommandOptions.name || commandName === helpCommandOptions.alias) {
// Stub for the `help` command
this.makeCommand(helpCommandOptions, [], () => {});
} else if (commandName === versionCommandOptions.name || commandName === helpCommandOptions.alias) {
// Stub for the `help` command
this.makeCommand(versionCommandOptions, [], () => {});
} else {
const builtInExternalCommandInfo = externalBuiltInCommandsInfo.find(
(externalBuiltInCommandInfo) =>
externalBuiltInCommandInfo.name === commandName || externalBuiltInCommandInfo.alias === commandName,
);
let pkg;
if (builtInExternalCommandInfo) {
({ pkg } = builtInExternalCommandInfo);
} else {
pkg = commandName;
}
if (pkg !== 'webpack-cli' && !getPkg(pkg)) {
if (!allowToInstall) {
return;
}
try {
pkg = await promptInstallation(pkg, () => {
logger.error(`For using this command you need to install: '${green(commandName)}' package`);
});
} catch (error) {
logger.error(`Action Interrupted, use '${cyan('webpack-cli help')}' to see possible commands`);
process.exit(2);
}
}
let loadedCommand;
try {
loadedCommand = require(pkg);
} catch (error) {
// Ignore, command is not installed
return;
}
if (loadedCommand.default) {
loadedCommand = loadedCommand.default;
}
let command;
try {
command = new loadedCommand();
await command.apply(this);
} catch (error) {
logger.error(`Unable to load '${pkg}' command`);
logger.error(error);
process.exit(2);
}
}
};
// Register own exit
this.program.exitOverride(async (error) => {
if (error.exitCode === 0) {
process.exit(0);
}
if (error.code === 'executeSubCommandAsync') {
process.exit(2);
}
if (error.code === 'commander.help') {
process.exit(0);
}
if (error.code === 'commander.unknownOption') {
let name = error.message.match(/'(.+)'/);
if (name) {
name = name[1].substr(2);
if (name.includes('=')) {
name = name.split('=')[0];
}
const { commandName } = getCommandNameAndOptions(this.program.args);
if (commandName) {
const command = this.program.commands.find(
(command) => command.name() === commandName || command.alias() === commandName,
);
if (!command) {
logger.error(`Can't find and load command '${commandName}'`);
logger.error("Run 'webpack --help' to see available commands and options");
process.exit(2);
}
const found = command.options.find((option) => distance(name, option.long.slice(2)) < 3);
if (found) {
logger.error(`Did you mean '--${found.name()}'?`);
}
}
}
}
// Codes:
// - commander.unknownCommand
// - commander.missingArgument
// - commander.missingMandatoryOptionValue
// - commander.optionMissingArgument
logger.error("Run 'webpack --help' to see available commands and options");
process.exit(2);
});
// Default `--color` and `--no-color` options
// TODO doesn't work with `webpack serve` (never work, need fix), `--stats` doesn't work too, other options are fine
let colorFromArguments;
this.program.option('--color', 'Enable colors on console.');
this.program.on('option:color', function () {
const { color } = this.opts();
colorFromArguments = color;
coloretteOptions.enabled = color;
});
this.program.option('--no-color', 'Disable colors on console.');
this.program.on('option:no-color', function () {
const { color } = this.opts();
colorFromArguments = color;
coloretteOptions.enabled = color;
});
// Make `-v, --version` options
// Make `version|v [commands...]` command
const outputVersion = async (options) => {
// Filter `bundle`, `version` and `help` commands
const possibleCommandNames = options.filter(
(options) =>
options !== bundleCommandOptions.name &&
options !== bundleCommandOptions.alias &&
options !== versionCommandOptions.name &&
options !== versionCommandOptions.alias &&
options !== helpCommandOptions.name &&
options !== helpCommandOptions.alias,
);
possibleCommandNames.forEach((possibleCommandName) => {
const isOption = possibleCommandName.startsWith('-');
if (!isOption) {
return;
}
logger.error(`Unknown option '${possibleCommandName}'`);
logger.error("Run 'webpack --help' to see available commands and options");
process.exit(2);
});
if (possibleCommandNames.length > 0) {
await Promise.all(possibleCommandNames.map((possibleCommand) => loadCommandByName(possibleCommand)));
for (const possibleCommandName of possibleCommandNames) {
const foundCommand = this.program.commands.find(
(command) => command.name() === possibleCommandName || command.alias() === possibleCommandName,
);
if (!foundCommand) {
logger.error(`Unknown command '${possibleCommandName}'`);
logger.error("Run 'webpack --help' to see available commands and options");
process.exit(2);
}
try {
const { name, version } = require(`${foundCommand.pkg}/package.json`);
logger.raw(`${name} ${version}`);
} catch (e) {
logger.error(`Error: External package '${foundCommand.pkg}' not found`);
process.exit(2);
}
}
}
const pkgJSON = require('../package.json');
logger.raw(`webpack ${webpack.version}`);
logger.raw(`webpack-cli ${pkgJSON.version}`);
if (getPkg('webpack-dev-server')) {
// eslint-disable-next-line
const { version } = require('webpack-dev-server/package.json');
logger.raw(`webpack-dev-server ${version}`);
}
process.exit(0);
};
this.program.option(
'-v, --version',
"Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and commands.",
);
// Default global `help` command
const outputHelp = async (options, isVerbose, program) => {
const isGlobal = options.length === 0;
const hideVerboseOptions = (command) => {
command.options = command.options.filter((option) => {
const foundOption = flags.find((flag) => {
if (option.negate && flag.negative) {
return `no-${flag.name}` === option.name();
}
return flag.name === option.name();
});
if (foundOption && foundOption.help) {
return foundOption.help === 'minimum';
}
return true;
});
};
if (isGlobal) {
const commandsToLoad = []
.concat(bundleCommandOptions)
.concat(helpCommandOptions)
.concat(versionCommandOptions)
.concat(externalBuiltInCommandsInfo);
for (const commandToLoad of commandsToLoad) {
await loadCommandByName(commandToLoad.name);
}
const bundleCommand = this.program.commands.find(
(command) => command.name() === bundleCommandOptions.name || command.alias() === bundleCommandOptions.alias,
);
if (!isVerbose) {
hideVerboseOptions(bundleCommand);
}
let helpInformation = bundleCommand
.helpInformation()
.trimRight()
.replace(bundleCommandOptions.description, 'The build tool for modern web applications.')
.replace(
/Usage:.+/,
'Usage: webpack [options]\nAlternative usage: webpack bundle [options]\nAlternative usage: webpack --config <config> [options]\nAlternative usage: webpack bundle --config <config> [options]',
);
logger.raw(helpInformation);
} else {
const [name, ...optionsWithoutCommandName] = options;
if (name.startsWith('-')) {
logger.error(`Unknown option '${name}'`);
logger.error("Run 'webpack --help' to see available commands and options");
process.exit(2);
}
optionsWithoutCommandName.forEach((option) => {
logger.error(`Unknown option '${option}'`);
logger.error("Run 'webpack --help' to see available commands and options");
process.exit(2);
});
await loadCommandByName(name);
const command = this.program.commands.find((command) => command.name() === name || command.alias() === name);
if (!command) {
logger.error(`Can't find and load command '${name}'`);
logger.error("Run 'webpack --help' to see available commands and options");
process.exit(2);
}
if (!isVerbose) {
hideVerboseOptions(command);
}
let helpInformation = command.helpInformation().trimRight();
if (name === bundleCommandOptions.name || name === bundleCommandOptions.alias) {
helpInformation = helpInformation
.replace(bundleCommandOptions.description, 'The build tool for modern web applications.')
.replace(
/Usage:.+/,
'Usage: webpack [options]\nAlternative usage: webpack bundle [options]\nAlternative usage: webpack --config <config> [options]\nAlternative usage: webpack bundle --config <config> [options]',
);
}
logger.raw(helpInformation);
}
const globalOptions = program.helpInformation().match(/Options:\n(?<globalOptions>.+)\nCommands:\n/s);
if (globalOptions && globalOptions.groups.globalOptions) {
logger.raw('\nGlobal options:');
logger.raw(globalOptions.groups.globalOptions.trimRight());
}
if (isGlobal) {
const globalCommands = program.helpInformation().match(/Commands:\n(?<globalCommands>.+)/s);
logger.raw('\nCommands:');
logger.raw(globalCommands.groups.globalCommands.trimRight());
}
logger.raw("\nTo see list of all supported commands and options run 'webpack --help=verbose'.\n");
logger.raw('Webpack documentation: https://webpack.js.org/.');
logger.raw('CLI documentation: https://webpack.js.org/api/cli/.');
logger.raw(`${bold('Made with ♥ by the webpack team')}.`);
process.exit(0);
};
this.program.helpOption(false);
this.program.addHelpCommand(false);
this.program.option('-h, --help [verbose]', 'Display help for commands and options.');
let isInternalActionCalled = false;
// Default action
this.program.usage('[options]');
this.program.allowUnknownOption(true);
this.program.action(async (program) => {
if (!isInternalActionCalled) {
isInternalActionCalled = true;
} else {
logger.error('No commands found to run');
process.exit(2);
}
const { commandName, options, isDefault } = getCommandNameAndOptions(program.args);
const opts = program.opts();
if (opts.help || commandName === helpCommandOptions.name || commandName === helpCommandOptions.alias) {
let isVerbose = false;
if (opts.help) {
if (typeof opts.help === 'string') {
if (opts.help !== 'verbose') {
logger.error("Unknown value for '--help' option, please use '--help=verbose'");
process.exit(2);
}
isVerbose = true;
}
}
this.program.forHelp = true;
const optionsForHelp = [].concat(opts.help && !isDefault ? [commandName] : []).concat(options);
await outputHelp(optionsForHelp, isVerbose, program);
}
if (opts.version || commandName === versionCommandOptions.name || commandName === versionCommandOptions.alias) {
const optionsForVersion = [].concat(opts.version ? [commandName] : []).concat(options);
await outputVersion(optionsForVersion, program);
}
await loadCommandByName(commandName, true);
await this.program.parseAsync([commandName, ...options], { from: 'user' });
});
await this.program.parseAsync(args);
}
async resolveConfig(options) {
const loadConfig = async (configPath) => {
const ext = extname(configPath);
const interpreted = Object.keys(jsVariants).find((variant) => variant === ext);
if (interpreted) {
rechoir.prepare(extensions, configPath);
}
const { pathToFileURL } = require('url');
let importESM;
try {
importESM = new Function('id', 'return import(id);');
} catch (e) {
importESM = null;
}
let options;
try {
try {
options = require(configPath);
} catch (error) {
if (pathToFileURL && importESM && error.code === 'ERR_REQUIRE_ESM') {
const urlForConfig = pathToFileURL(configPath);
options = await importESM(urlForConfig);
options = options.default;
return { options, path: configPath };
}
throw error;
}
} catch (error) {
logger.error(`Failed to load '${configPath}'`);
logger.error(error);
process.exit(2);
}
if (options.default) {
options = options.default;
}
return { options, path: configPath };
};
const evaluateConfig = async (loadedConfig, args) => {
const isMultiCompiler = Array.isArray(loadedConfig.options);
const config = isMultiCompiler ? loadedConfig.options : [loadedConfig.options];
let evaluatedConfig = await Promise.all(
config.map(async (rawConfig) => {
if (typeof rawConfig.then === 'function') {
rawConfig = await rawConfig;
}
// `Promise` may return `Function`
if (typeof rawConfig === 'function') {
// when config is a function, pass the env from args to the config function
rawConfig = await rawConfig(args.env, args);
}
return rawConfig;
}),
);
loadedConfig.options = isMultiCompiler ? evaluatedConfig : evaluatedConfig[0];
const isObject = (value) => typeof value === 'object' && value !== null;
if (!isObject(loadedConfig.options) && !Array.isArray(loadedConfig.options)) {
logger.error(`Invalid configuration in '${loadedConfig.path}'`);
process.exit(2);
}
return loadedConfig;
};
let config = { options: {}, path: new WeakMap() };
if (options.config && options.config.length > 0) {
const evaluatedConfigs = await Promise.all(
options.config.map(async (value) => {
const configPath = resolve(value);
if (!existsSync(configPath)) {
logger.error(`The specified config file doesn't exist in '${configPath}'`);
process.exit(2);
}
const loadedConfig = await loadConfig(configPath);
return evaluateConfig(loadedConfig, options);
}),
);
config.options = [];
evaluatedConfigs.forEach((evaluatedConfig) => {
if (Array.isArray(evaluatedConfig.options)) {
evaluatedConfig.options.forEach((options) => {
config.options.push(options);
config.path.set(options, evaluatedConfig.path);
});
} else {
config.options.push(evaluatedConfig.options);
config.path.set(evaluatedConfig.options, evaluatedConfig.path);
}
});
config.options = config.options.length === 1 ? config.options[0] : config.options;
} else {
// Order defines the priority, in increasing order
const defaultConfigFiles = ['webpack.config', '.webpack/webpack.config', '.webpack/webpackfile']
.map((filename) =>
// Since .cjs is not available on interpret side add it manually to default config extension list
[...Object.keys(extensions), '.cjs'].map((ext) => ({
path: resolve(filename + ext),
ext: ext,
module: extensions[ext],
})),
)
.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
let foundDefaultConfigFile;
for (const defaultConfigFile of defaultConfigFiles) {
if (existsSync(defaultConfigFile.path)) {
foundDefaultConfigFile = defaultConfigFile;
break;
}
}
if (foundDefaultConfigFile) {
const loadedConfig = await loadConfig(foundDefaultConfigFile.path);
const evaluatedConfig = await evaluateConfig(loadedConfig, options);
config.options = evaluatedConfig.options;
if (Array.isArray(config.options)) {
config.options.forEach((options) => {
config.path.set(options, evaluatedConfig.path);
});
} else {
config.path.set(evaluatedConfig.options, evaluatedConfig.path);
}
}
}
if (options.configName) {
const notfoundConfigNames = [];
config.options = options.configName.map((configName) => {
let found;
if (Array.isArray(config.options)) {
found = config.options.find((options) => options.name === configName);
} else {
found = config.options.name === configName ? config.options : undefined;
}
if (!found) {
notfoundConfigNames.push(configName);
}
return found;
});
if (notfoundConfigNames.length > 0) {
logger.error(
notfoundConfigNames.map((configName) => `Configuration with the name "${configName}" was not found.`).join(' '),
);
process.exit(2);
}
}
if (options.merge) {
// we can only merge when there are multiple configurations
// either by passing multiple configs by flags or passing a
// single config exporting an array
if (!Array.isArray(config.options) || config.options.length <= 1) {
logger.error('At least two configurations are required for merge.');
process.exit(2);
}
const mergedConfigPaths = [];
config.options = config.options.reduce((accumulator, options) => {
const configPath = config.path.get(options);
const mergedOptions = webpackMerge(accumulator, options);
mergedConfigPaths.push(configPath);
return mergedOptions;
}, {});
config.path.set(config.options, mergedConfigPaths);
}
return config;
}
// TODO refactor
async applyOptions(config, options) {
if (options.analyze) {
if (!getPkg('webpack-bundle-analyzer')) {
try {
await promptInstallation('webpack-bundle-analyzer', () => {
logger.error(`It looks like ${yellow('webpack-bundle-analyzer')} is not installed.`);
});
} catch (error) {
logger.error(`Action Interrupted, Please try once again or install ${yellow('webpack-bundle-analyzer')} manually.`);
process.exit(2);
}
logger.success(`${yellow('webpack-bundle-analyzer')} was installed successfully.`);
}
}
if (typeof options.progress === 'string' && options.progress !== 'profile') {
logger.error(`'${options.progress}' is an invalid value for the --progress option. Only 'profile' is allowed.`);
process.exit(2);
}
if (Object.keys(options).length === 0 && !process.env.NODE_ENV) {
return config;
}
if (cli) {
const processArguments = (configOptions) => {
const coreFlagMap = flags
.filter((flag) => flag.group === 'core')
.reduce((accumulator, flag) => {
accumulator[flag.name] = flag;
return accumulator;
}, {});
const CLIoptions = Object.keys(options).reduce((accumulator, name) => {
const kebabName = toKebabCase(name);
if (coreFlagMap[kebabName]) {
accumulator[kebabName] = options[name];
}
return accumulator;
}, {});
const problems = cli.processArguments(coreFlagMap, configOptions, CLIoptions);
if (problems) {
const capitalizeFirstLetter = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
};
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) => {
logger.error(
`${capitalizeFirstLetter(problem.type.replace(/-/g, ' '))}${
problem.value ? ` '${problem.value}'` : ''
} for the '--${problem.argument}' option${problem.index ? ` by index '${problem.index}'` : ''}`,
);
if (problem.expected) {
logger.error(`Expected: '${problem.expected}'`);
}
});
}
process.exit(2);
}
return configOptions;
};
config.options = Array.isArray(config.options)
? config.options.map((options) => processArguments(options))
: processArguments(config.options);
const setupDefaultOptions = (configOptions) => {
// No need to run for webpack@4
if (configOptions.cache && configOptions.cache.type === 'filesystem') {
const configPath = config.path.get(configOptions);
if (configPath) {
if (!configOptions.cache.buildDependencies) {
configOptions.cache.buildDependencies = {};
}
if (!configOptions.cache.buildDependencies.defaultConfig) {
configOptions.cache.buildDependencies.defaultConfig = [];
}
if (Array.isArray(configPath)) {
configPath.forEach((item) => {
configOptions.cache.buildDependencies.defaultConfig.push(item);
});
} else {
configOptions.cache.buildDependencies.defaultConfig.push(configPath);