-
Notifications
You must be signed in to change notification settings - Fork 1
/
源码5
614 lines (553 loc) · 17.8 KB
/
源码5
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
来看下/bin/convert-argv文件,这个文件主要是对命令参数的解析。
先看开头:
var path = require("path");
var fs = require("fs");
fs.existsSync = fs.existsSync || path.existsSync;
var interpret = require("interpret");
var prepareOptions = require("../lib/prepareOptions");
引入interpret模块,这是一个文件后缀集合的模块,
还有prepareOptions文件:内容如下,主要是对导出模块的处理,首先对是否是es6支持的export defalut支持还是module.export导出的,
然后判断导出的是否是数组进入判断,返回导出内容
module.exports = function prepareOptions(options, argv) {
argv = argv || {};
options = handleExport(options);
if(Array.isArray(options)) {
options = options.map(_options => handleFunction(_options, argv));
} else {
options = handleFunction(options, argv);
}
return options;
};
function handleExport(options) {
const isES6DefaultExported = (
typeof options === "object" && options !== null && typeof options.default !== "undefined"
);
options = isES6DefaultExported ? options.default : options;
return options;
}
function handleFunction(options, argv) {
if(typeof options === "function") {
options = options(argv.env, argv);
}
return options;
}
文件正文:
// 文件作为一个函数导出
module.exports = function(yargs, argv, convertOptions) {
// 其中yargs带表 配置参数,argv:命令解析组成的对象,convertOptions带表输出对象
options为一个初始数组
var options = [];
// 是否带有d参数,代表是否debug
// Shortcuts
if(argv.d) {
argv.debug = true;
argv["output-pathinfo"] = true;
if(!argv.devtool) {
argv.devtool = "eval-cheap-module-source-map";
}
}
// 参数p,是否压缩
if(argv.p) {
argv["optimize-minimize"] = true;
argv["define"] = [].concat(argv["define"] || []).concat("process.env.NODE_ENV=\"production\"");
}
// 设置configFileLoaded 为false,等文件调用并解析完之后设为true
var configFileLoaded = false;
// 参数文件设置空数组
var configFiles = [];
// 对各种扩展文件进行排序,js在前
var extensions = Object.keys(interpret.extensions).sort(function(a, b) {
return a === ".js" ? -1 : b === ".js" ? 1 : a.length - b.length;
});
// webpack默人的两个文件webpack.config webpackfile进行扩展的匹配,defaultConfigFiles带表webpack配置文件和扩展名组合的数组
var defaultConfigFiles = ["webpack.config", "webpackfile"].map(function(filename) {
return extensions.map(function(ext) {
return {
path: path.resolve(filename + ext),
ext: ext
};
});
}).reduce(function(a, i) {
return a.concat(i);
}, []);
var i;
// argv.config 带表是否webpack命令中有--config参数,后面是配置文件的相对路径 如:build/webpack.dev.conf.js
if(argv.config) {
// 获取配置文件的后缀
var getConfigExtension = function getConfigExtension(configPath) {
for(i = extensions.length - 1; i >= 0; i--) {
var tmpExt = extensions[i];
if(configPath.indexOf(tmpExt, configPath.length - tmpExt.length) > -1) {
return tmpExt;
}
}
return path.extname(configPath);
};
// 将相对路径转化为绝对路径,返回绝对路径和扩展名的对象
var mapConfigArg = function mapConfigArg(configArg) {
var resolvedPath = path.resolve(configArg);
var extension = getConfigExtension(resolvedPath);
return {
path: resolvedPath,
ext: extension
};
};
var configArgList = Array.isArray(argv.config) ? argv.config : [argv.config];
配置文件绝对路径和扩展名的对象的数组
configFiles = configArgList.map(mapConfigArg);
} else {
// 如果没有配置文件,就可默人的两个配置文件名和扩展名的组合逐一进行匹配
for(i = 0; i < defaultConfigFiles.length; i++) {
var webpackConfig = defaultConfigFiles[i].path;
if(fs.existsSync(webpackConfig)) {
configFiles.push({
path: webpackConfig,
ext: defaultConfigFiles[i].ext
});
break;
}
}
}
// 如果找到配置文件
if(configFiles.length > 0) {
var registerCompiler = function registerCompiler(moduleDescriptor) {
if(moduleDescriptor) {
if(typeof moduleDescriptor === "string") {
require(moduleDescriptor);
} else if(!Array.isArray(moduleDescriptor)) {
moduleDescriptor.register(require(moduleDescriptor.module));
} else {
for(var i = 0; i < moduleDescriptor.length; i++) {
try {
registerCompiler(moduleDescriptor[i]);
break;
} catch(e) {
// do nothing
}
}
}
}
};
var requireConfig = function requireConfig(configPath) {
var options = require(configPath);
options = prepareOptions(options, argv);
return options;
};
// options加入文件path
configFiles.forEach(function(file) {
registerCompiler(interpret.extensions[file.ext]);
options.push(requireConfig(file.path));
});
configFileLoaded = true;
}
if(!configFileLoaded) {
return processConfiguredOptions({});
} else if(options.length === 1) {
return processConfiguredOptions(options[0]);
} else {
return processConfiguredOptions(options);
}
// 执行回调
function processConfiguredOptions(options) {
// 如果返回为空或者不为对象,报错
if(options === null || typeof options !== "object") {
console.error("Config did not export an object or a function returning an object.");
process.exit(-1); // eslint-disable-line
}
// process Promise
// 支持票promise
if(typeof options.then === "function") {
return options.then(processConfiguredOptions);
}
// process ES6 default
// 支持es6
if(typeof options === "object" && typeof options.default === "object") {
return processConfiguredOptions(options.default);
}
// options多个,并且有config-name参数
// filter multi-config by name
if(Array.isArray(options) && argv["config-name"]) {
var namedOptions = options.filter(function(opt) {
return opt.name === argv["config-name"];
});
if(namedOptions.length === 0) {
console.error("Configuration with name '" + argv["config-name"] + "' was not found.");
process.exit(-1); // eslint-disable-line
} else if(namedOptions.length === 1) {
return processConfiguredOptions(namedOptions[0]);
}
options = namedOptions;
}
// 数组
if(Array.isArray(options)) {
options.forEach(processOptions);
} else {
processOptions(options);
}
// 绝对路径
if(argv.context) {
options.context = path.resolve(argv.context);
}
if(!options.context) {
options.context = process.cwd();
}
// 是否监听
if(argv.watch) {
options.watch = true;
}
// 监听间隔时间
if(argv["watch-aggregate-timeout"]) {
options.watchOptions = options.watchOptions || {};
options.watchOptions.aggregateTimeout = +argv["watch-aggregate-timeout"];
}
if(typeof argv["watch-poll"] !== "undefined") {
options.watchOptions = options.watchOptions || {};
if(argv["watch-poll"] === "true" || argv["watch-poll"] === "")
options.watchOptions.poll = true;
else if(!isNaN(argv["watch-poll"]))
options.watchOptions.poll = +argv["watch-poll"];
}
if(argv["watch-stdin"]) {
options.watchOptions = options.watchOptions || {};
options.watchOptions.stdin = true;
options.watch = true;
}
return options;
}
// process options的各种参数格式处理
function processOptions(options) {
var noOutputFilenameDefined = !options.output || !options.output.filename;
function ifArg(name, fn, init, finalize) {
if(Array.isArray(argv[name])) {
if(init) {
init();
}
argv[name].forEach(fn);
if(finalize) {
finalize();
}
} else if(typeof argv[name] !== "undefined" && argv[name] !== null) {
if(init) {
init();
}
fn(argv[name], -1);
if(finalize) {
finalize();
}
}
}
function ifArgPair(name, fn, init, finalize) {
ifArg(name, function(content, idx) {
var i = content.indexOf("=");
if(i < 0) {
return fn(null, content, idx);
} else {
return fn(content.substr(0, i), content.substr(i + 1), idx);
}
}, init, finalize);
}
function ifBooleanArg(name, fn) {
ifArg(name, function(bool) {
if(bool) {
fn();
}
});
}
function mapArgToBoolean(name, optionName) {
ifArg(name, function(bool) {
if(bool === true)
options[optionName || name] = true;
else if(bool === false)
options[optionName || name] = false;
});
}
// 这里特别指出,加载插件plugin,是找到路径,然后require,在new Plugin()
function loadPlugin(name) {
var loadUtils = require("loader-utils");
var args;
try {
var p = name && name.indexOf("?");
if(p > -1) {
args = loadUtils.parseQuery(name.substring(p));
name = name.substring(0, p);
}
} catch(e) {
console.log("Invalid plugin arguments " + name + " (" + e + ").");
process.exit(-1); // eslint-disable-line
}
var path;
try {
var resolve = require("enhanced-resolve");
path = resolve.sync(process.cwd(), name);
} catch(e) {
console.log("Cannot resolve plugin " + name + ".");
process.exit(-1); // eslint-disable-line
}
var Plugin;
try {
Plugin = require(path);
} catch(e) {
console.log("Cannot load plugin " + name + ". (" + path + ")");
throw e;
}
try {
return new Plugin(args);
} catch(e) {
console.log("Cannot instantiate plugin " + name + ". (" + path + ")");
throw e;
}
}
function ensureObject(parent, name) {
if(typeof parent[name] !== "object" || parent[name] === null) {
parent[name] = {};
}
}
function ensureArray(parent, name) {
if(!Array.isArray(parent[name])) {
parent[name] = [];
}
}
ifArgPair("entry", function(name, entry) {
if(typeof options.entry[name] !== "undefined" && options.entry[name] !== null) {
options.entry[name] = [].concat(options.entry[name]).concat(entry);
} else {
options.entry[name] = entry;
}
}, function() {
ensureObject(options, "entry");
});
function bindRules(arg) {
ifArgPair(arg, function(name, binding) {
if(name === null) {
name = binding;
binding += "-loader";
}
var rule = {
test: new RegExp("\\." + name.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "$"), // eslint-disable-line no-useless-escape
loader: binding
};
if(arg === "module-bind-pre") {
rule.enforce = "pre";
} else if(arg === "module-bind-post") {
rule.enforce = "post";
}
options.module.rules.push(rule);
}, function() {
ensureObject(options, "module");
ensureArray(options.module, "rules");
});
}
bindRules("module-bind");
bindRules("module-bind-pre");
bindRules("module-bind-post");
var defineObject;
ifArgPair("define", function(name, value) {
if(name === null) {
name = value;
value = true;
}
defineObject[name] = value;
}, function() {
defineObject = {};
}, function() {
ensureArray(options, "plugins");
var DefinePlugin = require("../lib/DefinePlugin");
options.plugins.push(new DefinePlugin(defineObject));
});
ifArg("output-path", function(value) {
ensureObject(options, "output");
options.output.path = path.resolve(value);
});
ifArg("output-filename", function(value) {
ensureObject(options, "output");
options.output.filename = value;
noOutputFilenameDefined = false;
});
ifArg("output-chunk-filename", function(value) {
ensureObject(options, "output");
options.output.chunkFilename = value;
});
ifArg("output-source-map-filename", function(value) {
ensureObject(options, "output");
options.output.sourceMapFilename = value;
});
ifArg("output-public-path", function(value) {
ensureObject(options, "output");
options.output.publicPath = value;
});
ifArg("output-jsonp-function", function(value) {
ensureObject(options, "output");
options.output.jsonpFunction = value;
});
ifBooleanArg("output-pathinfo", function() {
ensureObject(options, "output");
options.output.pathinfo = true;
});
ifArg("output-library", function(value) {
ensureObject(options, "output");
options.output.library = value;
});
ifArg("output-library-target", function(value) {
ensureObject(options, "output");
options.output.libraryTarget = value;
});
ifArg("records-input-path", function(value) {
options.recordsInputPath = path.resolve(value);
});
ifArg("records-output-path", function(value) {
options.recordsOutputPath = path.resolve(value);
});
ifArg("records-path", function(value) {
options.recordsPath = path.resolve(value);
});
ifArg("target", function(value) {
options.target = value;
});
mapArgToBoolean("cache");
ifBooleanArg("hot", function() {
ensureArray(options, "plugins");
var HotModuleReplacementPlugin = require("../lib/HotModuleReplacementPlugin");
options.plugins.push(new HotModuleReplacementPlugin());
});
ifBooleanArg("debug", function() {
ensureArray(options, "plugins");
var LoaderOptionsPlugin = require("../lib/LoaderOptionsPlugin");
options.plugins.push(new LoaderOptionsPlugin({
debug: true
}));
});
ifArg("devtool", function(value) {
options.devtool = value;
});
function processResolveAlias(arg, key) {
ifArgPair(arg, function(name, value) {
if(!name) {
throw new Error("--" + arg + " <string>=<string>");
}
ensureObject(options, key);
ensureObject(options[key], "alias");
options[key].alias[name] = value;
});
}
processResolveAlias("resolve-alias", "resolve");
processResolveAlias("resolve-loader-alias", "resolveLoader");
ifArg("resolve-extensions", function(value) {
ensureObject(options, "resolve");
if(Array.isArray(value)) {
options.resolve.extensions = value;
} else {
options.resolve.extensions = value.split(/,\s*/);
}
});
ifArg("optimize-max-chunks", function(value) {
ensureArray(options, "plugins");
var LimitChunkCountPlugin = require("../lib/optimize/LimitChunkCountPlugin");
options.plugins.push(new LimitChunkCountPlugin({
maxChunks: parseInt(value, 10)
}));
});
ifArg("optimize-min-chunk-size", function(value) {
ensureArray(options, "plugins");
var MinChunkSizePlugin = require("../lib/optimize/MinChunkSizePlugin");
options.plugins.push(new MinChunkSizePlugin({
minChunkSize: parseInt(value, 10)
}));
});
ifBooleanArg("optimize-minimize", function() {
ensureArray(options, "plugins");
var UglifyJsPlugin = require("../lib/optimize/UglifyJsPlugin");
var LoaderOptionsPlugin = require("../lib/LoaderOptionsPlugin");
options.plugins.push(new UglifyJsPlugin({
sourceMap: options.devtool && (options.devtool.indexOf("sourcemap") >= 0 || options.devtool.indexOf("source-map") >= 0)
}));
options.plugins.push(new LoaderOptionsPlugin({
minimize: true
}));
});
ifArg("prefetch", function(request) {
ensureArray(options, "plugins");
var PrefetchPlugin = require("../lib/PrefetchPlugin");
options.plugins.push(new PrefetchPlugin(request));
});
ifArg("provide", function(value) {
ensureArray(options, "plugins");
var idx = value.indexOf("=");
var name;
if(idx >= 0) {
name = value.substr(0, idx);
value = value.substr(idx + 1);
} else {
name = value;
}
var ProvidePlugin = require("../lib/ProvidePlugin");
options.plugins.push(new ProvidePlugin(name, value));
});
ifArg("plugin", function(value) {
ensureArray(options, "plugins");
options.plugins.push(loadPlugin(value));
});
mapArgToBoolean("bail");
mapArgToBoolean("profile");
if(noOutputFilenameDefined) {
ensureObject(options, "output");
if(convertOptions && convertOptions.outputFilename) {
options.output.path = path.resolve(path.dirname(convertOptions.outputFilename));
options.output.filename = path.basename(convertOptions.outputFilename);
} else if(argv._.length > 0) {
options.output.filename = argv._.pop();
options.output.path = path.resolve(path.dirname(options.output.filename));
options.output.filename = path.basename(options.output.filename);
} else if(configFileLoaded) {
throw new Error("'output.filename' is required, either in config file or as --output-filename");
} else {
console.error("No configuration file found and no output filename configured via CLI option.");
console.error("A configuration file could be named 'webpack.config.js' in the current directory.");
console.error("Use --help to display the CLI options.");
process.exit(-1); // eslint-disable-line
}
}
if(argv._.length > 0) {
if(Array.isArray(options.entry) || typeof options.entry === "string") {
options.entry = {
main: options.entry
};
}
ensureObject(options, "entry");
var addTo = function addTo(name, entry) {
if(options.entry[name]) {
if(!Array.isArray(options.entry[name])) {
options.entry[name] = [options.entry[name]];
}
options.entry[name].push(entry);
} else {
options.entry[name] = entry;
}
};
argv._.forEach(function(content) {
var i = content.indexOf("=");
var j = content.indexOf("?");
if(i < 0 || (j >= 0 && j < i)) {
var resolved = path.resolve(content);
if(fs.existsSync(resolved)) {
addTo("main", `${resolved}${fs.statSync(resolved).isDirectory() ? path.sep : ""}`);
} else {
addTo("main", content);
}
} else {
addTo(content.substr(0, i), content.substr(i + 1));
}
});
}
if(!options.entry) {
if(configFileLoaded) {
console.error("Configuration file found but no entry configured.");
} else {
console.error("No configuration file found and no entry configured via CLI option.");
console.error("When using the CLI you need to provide at least two arguments: entry and output.");
console.error("A configuration file could be named 'webpack.config.js' in the current directory.");
}
console.error("Use --help to display the CLI options.");
process.exit(-1); // eslint-disable-line
}
}
};