/
webpack-cli.js
274 lines (237 loc) · 9.66 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
const { packageExists } = require('./utils/package-exists');
const webpack = packageExists('webpack') ? require('webpack') : undefined;
const cliLogger = require('./utils/logger');
const webpackMerge = require('webpack-merge');
const { core, coreFlagMap } = require('./utils/cli-flags');
const argParser = require('./utils/arg-parser');
const { outputStrategy } = require('./utils/merge-strategies');
const assignFlagDefaults = require('./utils/flag-defaults');
const { writeFileSync } = require('fs');
const WebpackCLIPlugin = require('./plugins/WebpackCLIPlugin');
const { getStatsOptions } = require('./utils/stats-options');
const { PluginName } = require('./utils/name');
// CLI arg resolvers
const handleConfigResolution = require('./groups/ConfigGroup');
const resolveMode = require('./groups/resolveMode');
const resolveStats = require('./groups/resolveStats');
const resolveOutput = require('./groups/resolveOutput');
const basicResolver = require('./groups/basicResolver');
const resolveAdvanced = require('./groups/resolveAdvanced');
const { toKebabCase } = require('./utils/helpers');
class WebpackCLI {
constructor() {
this.compilerConfiguration = {};
this.outputConfiguration = {};
}
/**
* Responsible for handling flags coming from webpack/webpack
* @private\
* @returns {void}
*/
_handleCoreFlags(parsedArgs) {
const coreCliHelper = require('webpack').cli;
if (!coreCliHelper) return;
const coreConfig = Object.keys(parsedArgs)
.filter((arg) => {
return coreFlagMap.has(toKebabCase(arg));
})
.reduce((acc, cur) => {
acc[toKebabCase(cur)] = parsedArgs[cur];
return acc;
}, {});
const coreCliArgs = coreCliHelper.getArguments();
// Merge the core flag config with the compilerConfiguration
coreCliHelper.processArguments(coreCliArgs, this.compilerConfiguration, coreConfig);
// Assign some defaults to core flags
const configWithDefaults = assignFlagDefaults(this.compilerConfiguration, parsedArgs);
this._mergeOptionsToConfiguration(configWithDefaults);
}
async _baseResolver(cb, parsedArgs, strategy) {
const resolvedConfig = await cb(parsedArgs, this.compilerConfiguration);
this._mergeOptionsToConfiguration(resolvedConfig.options, strategy);
this._mergeOptionsToOutputConfiguration(resolvedConfig.outputOptions);
}
/**
* Expose commander argParser
* @param {...any} args args for argParser
*/
argParser(...args) {
return argParser(...args);
}
getCoreFlags() {
return core;
}
/**
* Responsible to override webpack options.
* @param {Object} options The options returned by a group helper
* @param {Object} strategy The strategy to pass to webpack-merge. The strategy
* is implemented inside the group helper
* @private
* @returns {void}
*/
_mergeOptionsToConfiguration(options, strategy) {
/**
* options where they differ per config use this method to apply relevant option to relevant config
* eg mode flag applies per config
*/
if (Array.isArray(options) && Array.isArray(this.compilerConfiguration)) {
this.compilerConfiguration = options.map((option, index) => {
const compilerConfig = this.compilerConfiguration[index];
if (strategy) {
return webpackMerge.strategy(strategy)(compilerConfig, option);
}
return webpackMerge(compilerConfig, option);
});
return;
}
/**
* options is an array (multiple configuration) so we create a new
* configuration where each element is individually merged
*/
if (Array.isArray(options)) {
this.compilerConfiguration = options.map((configuration) => {
if (strategy) {
return webpackMerge.strategy(strategy)(this.compilerConfiguration, configuration);
}
return webpackMerge(this.compilerConfiguration, configuration);
});
} else {
/**
* The compiler configuration is already an array, so for each element
* we merge the options
*/
if (Array.isArray(this.compilerConfiguration)) {
this.compilerConfiguration = this.compilerConfiguration.map((thisConfiguration) => {
if (strategy) {
return webpackMerge.strategy(strategy)(thisConfiguration, options);
}
return webpackMerge(thisConfiguration, options);
});
} else {
if (strategy) {
this.compilerConfiguration = webpackMerge.strategy(strategy)(this.compilerConfiguration, options);
} else {
this.compilerConfiguration = webpackMerge(this.compilerConfiguration, options);
}
}
}
}
/**
* Responsible for creating and updating the new output configuration
*
* @param {Object} options Output options emitted by the group helper
* @private
* @returns {void}
*/
_mergeOptionsToOutputConfiguration(options) {
if (options) {
this.outputConfiguration = Object.assign(this.outputConfiguration, options);
}
}
/**
* It runs in a fancy order all the expected groups.
* Zero config and configuration goes first.
*
* The next groups will override existing parameters
* @returns {Promise<void>} A Promise
*/
async runOptionGroups(parsedArgs) {
await Promise.resolve()
.then(() => this._baseResolver(handleConfigResolution, parsedArgs))
.then(() => this._baseResolver(resolveMode, parsedArgs))
.then(() => this._baseResolver(resolveOutput, parsedArgs, outputStrategy))
.then(() => this._handleCoreFlags(parsedArgs))
.then(() => this._baseResolver(basicResolver, parsedArgs))
.then(() => this._baseResolver(resolveAdvanced, parsedArgs))
.then(() => this._baseResolver(resolveStats, parsedArgs));
}
resolveLogger(compiler) {
return compiler ? compiler.getInfrastructureLogger(PluginName) : cliLogger;
}
handleError(error, compiler) {
const logger = this.resolveLogger(compiler);
// https://github.com/webpack/webpack/blob/master/lib/index.js#L267
// https://github.com/webpack/webpack/blob/v4.44.2/lib/webpack.js#L90
const ValidationError = webpack.ValidationError || webpack.WebpackOptionsValidationError;
// In case of schema errors print and exit process
// For webpack@4 and webpack@5
if (error instanceof ValidationError) {
logger.error(error.message);
} else {
logger.error(error);
}
}
createCompiler(options, callback) {
let compiler;
try {
compiler = webpack(options, callback);
} catch (error) {
this.handleError(error, compiler);
process.exit(2);
}
return compiler;
}
async getCompiler(args) {
await this.runOptionGroups(args);
return this.createCompiler(this.compilerConfiguration);
}
async run(args) {
await this.runOptionGroups(args);
let compiler;
let options = this.compilerConfiguration;
let outputOptions = this.outputConfiguration;
const isJsonOutput = typeof outputOptions.json !== 'undefined';
if (!isJsonOutput) {
const webpackCLIPlugin = new WebpackCLIPlugin({
progress: outputOptions.progress,
});
const addPlugin = (options) => {
if (!options.plugins) {
options.plugins = [];
}
options.plugins.unshift(webpackCLIPlugin);
};
if (Array.isArray(options)) {
options.forEach(addPlugin);
} else {
addPlugin(options);
}
}
const callback = (error, stats) => {
if (error) {
this.handleError(error, compiler);
process.exit(2);
}
if (stats.hasErrors()) {
process.exitCode = 1;
}
const logger = this.resolveLogger(compiler);
if (isJsonOutput) {
process.nextTick(() => {
const statsOptions = compiler.compilers
? { children: compiler.compilers.map(getStatsOptions) }
: getStatsOptions(compiler);
const json = JSON.stringify(stats.toJson(statsOptions), null, 2);
if (typeof outputOptions.json === 'string') {
try {
writeFileSync(outputOptions.json, json);
logger.info(`stats are successfully stored as json to ${outputOptions.json}`);
} catch (error) {
logger.error(error);
process.exit(2);
}
} else {
process.stdout.write(json + '\n');
}
});
}
};
compiler = this.createCompiler(options, callback);
if (compiler && outputOptions.interactive) {
const interactive = require('./utils/interactive');
interactive(compiler, options, outputOptions);
}
return Promise.resolve();
}
}
module.exports = WebpackCLI;