webpack-cli的cli.js源码阅读

344 阅读1分钟

wewebpack-cli要做的事情:

  • 使用yargs获取到命令行的参数,并对参数进行转换,生产编译的配置项。

  • 引用webpack,根据配置项进行编译和构建。

webpack-cli/bin/cli.js源码:

#!/usr/bin/env node

"use strict";

const Module = require("module");
// originalModuleCompile为一个函数
const originalModuleCompile = Module.prototype._compile;

// 使用v8的编译缓存
require("v8-compile-cache");

const importLocal = require("import-local");
const runCLI = require("../lib/bootstrap");
const utils = require("../lib/utils");

// 是否获取的是本地的node_mpdules
if (!process.env.WEBPACK_CLI_SKIP_IMPORT_LOCAL) {
    // Prefer the local installation of `webpack-cli`
    if (importLocal(__filename)) {
        return;
    }
}

process.title = "webpack";
// webpack存在,直接执行cli
if (utils.packageExists("webpack")) {
    runCLI(process.argv, originalModuleCompile);
} else {
    const { promptInstallation, logger, colors } = utils;

   // 控制台显示没有下载webpack的提示,然后下载,下载成功后,提示成功,并执行cli。
    promptInstallation("webpack", () => {
        utils.logger.error(`It looks like ${colors.bold("webpack")} is not installed.`);
    })
        .then(() => {
            logger.success(`${colors.bold("webpack")} was installed successfully.`);

            runCLI(process.argv, originalModuleCompile);
        })
        .catch(() => {
            logger.error(
                `Action Interrupted, Please try once again or install ${colors.bold(
                    "webpack",
                )} manually.`,
            );

            process.exit(2);
        });
}