const importLocal = require("import-local");
// Prefer the local installation of webpack-cli
if (importLocal(__filename)) {
return;
}
本地如果安装了webpack-cli,就用本地安装版本,不用全局的。
// yargs will terminate the process early when the user uses help or version.
// This causes large help outputs to be cut short (https://github.com/nodejs/node/wiki/API-changes-between-v0.10-and-v4#process).
// To prevent this we use the yargs.parse API and exit the process normally
yargs.parse(process.argv.slice(2), (err, argv, output) => {
Error.stackTraceLimit = 30;
// arguments validation failed
if (err && output) {
console.error(output);
process.exitCode = 1;
return;
}
// help or version info
if (output) {
console.log(output);
return;
}
if (argv.verbose) {
argv["display"] = "verbose";
}
根据当前命令行参数,格式化参数和处理输出。注意参数取slice(2),
let options;
try {
options = require("./utils/convert-argv")(argv);
} catch (err) {
if (err.code === "MODULE_NOT_FOUND") {
const moduleName = err.message.split("'")[1];
let instructions = "";
let errorMessage = "";
if (moduleName === "webpack") {
errorMessage = `\n${moduleName} not installed`;
instructions = `Install webpack to start bundling: \u001b[32m\n $ npm install --save-dev ${moduleName}\n`;
/**
* When --silent flag is present, an object with a no-op write method is
* used in place of process.stout
*/
const stdout = argv.silent ? { write: () => {} } : process.stdout;
参数开启静默模式,就用空输出函数。不是标准输出。
function ifArg(name, fn, init) {
if (Array.isArray(argv[name])) {
if (init) init();
argv[name].forEach(fn);
} else if (typeof argv[name] !== "undefined") {
if (init) init();
fn(argv[name], -1);
}
}
这个函数好,从命令行取参数值,并且执行传入的函数,函数参数时从命令行取的参数值。兼容数组,遍历执行。
function processOptions(options) {
// process Promise
if (typeof options.then === "function") {
options.then(processOptions).catch(function(err) {
console.error(err.stack || err);
// eslint-disable-next-line no-process-exit
process.exit(1);
});
return;
}