Webpack-cli构建流程

476 阅读1分钟

配置webpack.config.js

const path = require('path')
module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname,'dist')
  }
}


通过npm run build

 "build": "webpack"

在node_modules/.bin/webpack.cmd 下找入口文件

node "%~dp0\..\webpack\bin\webpack.js" %*

通过node_modules/webpack/bin/webpack.js 判断是否安装了webpack_cli 如果安装,执行runCli

webpack-cli/bin/cli.js 

require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));

cli.js 引入bootstrap bootstrape 中引入require('./webpack-cli') 创建WebpackCli 执行run

bootstrap.js

const WebpackCLI = require("./webpack-cli");

const runCLI = async (args) => {
  // Create a new instance of the CLI object
  const cli = new WebpackCLI();

  try {
    await cli.run(args);
  } catch (error) {
    cli.logger.error(error);
    process.exit(2);
  }
};

module.exports = runCLI;

调用require("./webpack-cli"); 在webpack-cli.js中,执行构造函数WebPackCli 的constructor

run方法:


 const cli = this;
    this.program.option("--color", "Enable colors on console.");
    this.program.on("option:color", function () {
     ...
    });
    ...
      this.program.usage("[options]");
    this.program.allowUnknownOption(true);
    this.program.action(async (options, program) => {
      ...
      await this.program.parseAsync([commandToRun, ...commandOperands, ...unknown], {
        from: "user",
      });
    });
    
    await this.program.parseAsync(args, parseOptions);

通过 await this.program.parseAsync(args, parseOptions); 触发this.program.action

  • 在this.program.action解析program参数
  • 加载loadCommandByName()
  • 通过参数创建命令 makeCommand 传入两个回调函数 (callback1,callback2)
        await this.makeCommand(
          isBuildCommandUsed ? buildCommandOptions : watchCommandOptions,
          async () => {
            //callback1
            this.webpack = await this.loadWebpack();

            return isWatchCommandUsed
              ? this.getBuiltInOptions().filter((option) => option.name !== "watch")
              : this.getBuiltInOptions();
          },
          async (entries, options) => {
            //callback2
            if (entries.length > 0) {
              options.entry = [...entries, ...(options.entry || [])];
            }

            await this.runWebpack(options, isWatchCommandUsed);
          },
        );

在runWebpack中 this.runWebpack创建了一个compiler

  async runWebpack(options, isWatchCommand) {
//创建compiler

    compiler = await this.createCompiler(options, callback);
在compiler中

  async createCompiler(options, callback) {
    //加载配置参数  调用webpack方法 接收配置文件 生成compiler

    let config = await this.loadConfig(options);
    config = await this.buildConfig(config, options);

    let compiler;
    //调用webpack.js  将webpack导入

    try {
      compiler = this.webpack(
        config.options,
        callback
          ? (error, stats) => {
              if (error && this.isValidationError(error)) {
                this.logger.error(error.message);
                process.exit(2);
              }

              callback(error, stats);
            }
          : callback,
      );
    } 
    return compiler;
  }
  }

webpack打包 使用webpack函数来接收config 调用run方法

//引入webpack
const webpack = require("webpack");

//引入webpack.config.js
const config = require("./webpack.config");
//调用webpack 获取compiler
let compiler = webpack(config)

//运行run方法
compiler.run((err, status) => {
  console.log(status,"webpack")
});