寻找webpack打包入口

node_modules.bin目录下有一个webpack.cmd脚本文件,组装定位了要执行的webpack.js文件

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

将启动文件指向了webpack目录下的bin\webpack.js
webpack.js文件中,有一个runCommond方法和isInstalled判断包是否安装函数,
const runCommand = (command, args) => { const cp = require("child_process"); return new Promise((resolve, reject) => { const executedCommand = cp.spawn(command, args, { stdio: "inherit", shell: true }); executedCommand.on("error", error => { reject(error); }); executedCommand.on("exit", code => { if (code === 0) { resolve(); } else { reject(); } }); }); }; const isInstalled = packageName => { try { require.resolve(packageName); return true; } catch (err) { return false; } };

installedClis获取已经安装的cli,这里面重要的就是CLIs数组中第一行isInstalled("webpack-cli"),指向了webpack-cli
const installedClis = CLIs.filter(cli => cli.installed);

接下来根据filter方法找到已经安装包,处理了包路径,通过最后的require导入了wbpack-cli/bin/cli.js
const path = require("path"); const pkgPath = require.resolve(`${installedClis[0].package}/package.json`); // eslint-disable-next-line node/no-missing-require const pkg = require(pkgPath); // eslint-disable-next-line node/no-missing-require require(path.resolve( path.dirname(pkgPath), pkg.bin[installedClis[0].binName] ));

wbpack-cli/bin/cli.js中,是一个IIFE,一般的cli文件中一般有二个操作,处理参数,将参数交给不同的逻辑(分发业务),文件中导入webpack,创建一个webpack实例。根据参数options创建一个compile实例,挂载钩子,
const webpack = require("webpack"); let lastHash = null; let compiler; try { compiler = webpack(options); } catch (err) { if (err.name === "WebpackOptionsValidationError") { if (argv.color) console.error(`\u001b[1m\u001b[31m${err.message}\u001b[39m\u001b[22m`); else console.error(err.message); // eslint-disable-next-line no-process-exit process.exit(1); }throw err; }

【寻找webpack打包入口】在文件结尾处,就找到了webpack打包入口run方法
compiler.run((err, stats) => { if (compiler.close) { compiler.close(err2 => { compilerCallback(err || err2, stats); }); } else { compilerCallback(err, stats); } });

    推荐阅读