# 一.webpack
# 1.npm 启动
# 2.调用 webpack-cli
# 3.进入 webpack
解析 webpack 包进入node_modules/webpack/bin/webpack.js
// 判断是否有安装webpack-cli、webpack-command包
const installedClis = CLIs.filter((cli) => cli.installed)
if (installedClis.length === 0) {
// 1.没有安装webpack-cli、webpack-command这两个包,先提示错误信息需要安装webpack cli 然后指导用户安装
} else if (installedClis.length === 1) {
// 2.安装了webpack-cli、webpack-command其中一个包
const path = require("path")
const pkgPath = require.resolve(`${installedClis[0].package}/package.json`)
const pkg = require(pkgPath)
require(path.resolve(
//解析webpack-cli 或者 webpack-command 包
path.dirname(pkgPath),
pkg.bin[installedClis[0].binName]
))
} else {
// 3.安装了webpack-cli、webpack-command这两个包,提示错误信息需要卸载其中一个包
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
解析 webpack-cli 包进入node_modules/webpack-cli/package.json
{
...
"bin": {
"webpack-cli": "./bin/cli.js"
},
...
}
1
2
3
4
5
6
7
2
3
4
5
6
7
实际上就是
require("node_modules/webpack-cli/bin/cli.js")
1
解析 node_modules/webpack-cli/bin/cli.js
// 存在webpack这个包
if (utils.packageExists("webpack")) {
runCLI(process.argv, originalModuleCompile)
}
1
2
3
4
2
3
4
解析 node_modules/webpack-cli/lib/bootstrap.js
const runCLI = async (args, originalModuleCompile) => {
try {
// 首先实例化WebpackCLI
const cli = new WebpackCLI()
cli._originalModuleCompile = originalModuleCompile
// 然后调用上面的run方法
await cli.run(args)
} catch (error) {
utils.logger.error(error)
process.exit(2)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
解析 node_modules/webpack-cli/lib/webpack-cli.js
拿到 WebpackCLI 实现 cli.run
class WebpackCLI {
constructor() {
// 实例化WebpackCLI时,会解析webpack这个包
this.webpack = require(process.env.WEBPACK_PACKAGE || "webpack")
}
// cli.run时会执行以下逻辑
async run(args, parseOptions) {
const loadCommandByName = async (commandName, allowToInstall = false) => {
await this.runWebpack(options, isWatchCommandUsed)
}
this.program.action(async (options, program) => {
await loadCommandByName(commandToRun, true)
})
}
async runWebpack(options, isWatchCommand) {
const callback = (error, stats) => {}
compiler = await this.createCompiler(options, callback)
}
async createCompiler(options, callback) {
this.applyNodeEnv(options)
let config = await this.resolveConfig(options)
config = await this.applyOptions(config, options)
config = await this.applyCLIPlugin(config, options)
let compiler
compiler = this.webpack(config.options, callback)
return compiler
}
}
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
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