• webpack原理篇(五十一):webpack启动过程分析


    说明

    玩转 webpack 学习笔记

    开始:从 webpack 命令行说起

    通过 npm scripts 运行 webpack

    • 开发环境:npm run dev
    • 生产环境:npm run build

    通过 webpack 直接运行

    • webpack entry.js bundle.js

    查找 webpack 入口文件

    在命令行运行以上命令后,npm会让命令行工具进入 node_modules\.bin 目录查找是否存在 webpack.sh 或者 webpack.cmd 文件,如果存在,就执行,不存在,就抛出错误。

    在这里插入图片描述

    实际的入口文件是:node_modules\webpack\bin\webpack.js

    在这里插入图片描述

    分析 webpack 的入口文件:webpack.js

    在这里插入图片描述

    源代码如下:

    #!/usr/bin/env node
    
    // @ts-ignore
    // 1# 正常执行返回
    process.exitCode = 0;
    
    /**
     * @param {string} command process to run
     * @param {string[]} args commandline arguments
     * @returns {Promise} promise
     */
     // 2# 运行某个命令
    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();
    			}
    		});
    	});
    };
    
    /**
     * @param {string} packageName name of the package
     * @returns {boolean} is the package installed?
     */
    // 3# 判断某个包是否安装
    const isInstalled = packageName => {
    	try {
    		require.resolve(packageName);
    
    		return true;
    	} catch (err) {
    		return false;
    	}
    };
    
    /**
     * @typedef {Object} CliOption
     * @property {string} name display name
     * @property {string} package npm package name
     * @property {string} binName name of the executable file
     * @property {string} alias shortcut for choice
     * @property {boolean} installed currently installed?
     * @property {boolean} recommended is recommended
     * @property {string} url homepage
     * @property {string} description description
     */
    
    /** @type {CliOption[]} */
    // 4# webpack 可用 cli webpack-cli(功能丰富一点) 跟 webpack-command
    const CLIs = [
    	{
    		name: "webpack-cli",
    		package: "webpack-cli",
    		binName: "webpack-cli",
    		alias: "cli",
    		installed: isInstalled("webpack-cli"),
    		recommended: true,
    		url: "https://github.com/webpack/webpack-cli",
    		description: "The original webpack full-featured CLI."
    	},
    	{
    		name: "webpack-command",
    		package: "webpack-command",
    		binName: "webpack-command",
    		alias: "command",
    		installed: isInstalled("webpack-command"),
    		recommended: false,
    		url: "https://github.com/webpack-contrib/webpack-command",
    		description: "A lightweight, opinionated webpack CLI."
    	}
    ];
    // 5# 判断两个是否都安装了
    const installedClis = CLIs.filter(cli => cli.installed);
    // 6# 根据安装的数量进行处理
    if (installedClis.length === 0) {
    	const path = require("path");
    	const fs = require("fs");
    	const readLine = require("readline");
    
    	let notify =
    		"One CLI for webpack must be installed. These are recommended choices, delivered as separate packages:";
    
    	for (const item of CLIs) {
    		if (item.recommended) {
    			notify += `\n - ${item.name} (${item.url})\n   ${item.description}`;
    		}
    	}
    
    	console.error(notify);
    
    	const isYarn = fs.existsSync(path.resolve(process.cwd(), "yarn.lock"));
    
    	const packageManager = isYarn ? "yarn" : "npm";
    	const installOptions = [isYarn ? "add" : "install", "-D"];
    
    	console.error(
    		`We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join(
    			" "
    		)}".`
    	);
    
    	const question = `Do you want to install 'webpack-cli' (yes/no): `;
    
    	const questionInterface = readLine.createInterface({
    		input: process.stdin,
    		output: process.stderr
    	});
    	questionInterface.question(question, answer => {
    		questionInterface.close();
    
    		const normalizedAnswer = answer.toLowerCase().startsWith("y");
    
    		if (!normalizedAnswer) {
    			console.error(
    				"You need to install 'webpack-cli' to use webpack via CLI.\n" +
    					"You can also install the CLI manually."
    			);
    			process.exitCode = 1;
    
    			return;
    		}
    
    		const packageName = "webpack-cli";
    
    		console.log(
    			`Installing '${packageName}' (running '${packageManager} ${installOptions.join(
    				" "
    			)} ${packageName}')...`
    		);
    
    		runCommand(packageManager, installOptions.concat(packageName))
    			.then(() => {
    				require(packageName); //eslint-disable-line
    			})
    			.catch(error => {
    				console.error(error);
    				process.exitCode = 1;
    			});
    	});
    } else if (installedClis.length === 1) {
    	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]
    	));
    } else {
    	console.warn(
    		`You have installed ${installedClis
    			.map(item => item.name)
    			.join(
    				" and "
    			)} together. To work with the "webpack" command you need only one CLI package, please remove one of them or use them directly via their binary.`
    	);
    
    	// @ts-ignore
    	process.exitCode = 1;
    }
    
    • 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
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175

    启动后的结果

    webpack 最终找到 webpack-cli (webpack-command) 这个 npm 包,并且执行 CLI。

  • 相关阅读:
    小几届的学弟问我,软件测试岗是选11k的华为还是20k的小公司,我直呼受不了,太凡尔赛了~
    JAVA基础(三十一)——反射之类加载
    vscode用vue框架写一个登陆页面
    swiper高度自适应
    MySQL视图
    TCP MIN_RTO 辩证考
    线性代数矩阵相关知识回顾
    ChatGLM-6B+LangChain与训练及模型微调教程
    MYSQL索引详解和优化
    全面掌握胶囊网络:从基础理论到PyTorch实战
  • 原文地址:https://blog.csdn.net/kaimo313/article/details/126458357