当前位置:网站首页>Webapck packaging principle -- Analysis of startup process
Webapck packaging principle -- Analysis of startup process
2022-07-01 06:47:00 【zxuanxuanz】
One 、 Run the command
(1)npm script
// development environment
npm run dev
// Production environment
npm run build(2)webpack Direct execution
webpack entry.js bundle.jsTwo 、 lookup Webpack Entrance file
(1) After running the above command on the command line ,npm Will let the command-line tool enter node_modules\.bin Find out whether the directory exists webpack.sh perhaps webpack.cmd file , If there is , Is executed , non-existent , Just throw the error .
(2) The actual entry file is :node_modules\webpack\bin\webpack.js
3、 ... and 、webpack Entry file :webpack.js analysis
#!/usr/bin/env node
// @ts-ignore
// Normal execution return (exitCode by 0,error by null), Error reporting will be modified exitCode meanwhile throw error
process.exitCode = 0;
/**
* @param {string} command process to run
* @param {string[]} args commandline arguments
* @returns {Promise<void>} promise
*/
// Run a command
//command:npm
//arg: install xxx -d
// Provide a solution to quickly execute a command , There is no need to manually enter commands on the command line
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?
*/
// Determine whether a package is installed
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
*/
//webpack Usable CLI:webpack-cli and webpack-command
/** @type {CliOption[]} */
const CLIs = [
// It has rich features
{
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."
},
// Relatively lighter
{
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."
}
];
// Whether two CLI Is... Installed
const installedClis = CLIs.filter(cli => cli.installed);
// One is not installed
if (installedClis.length === 0) {
const path = require("path");
const fs = require("fs");
const readLine = require("readline");
// Error message
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);
// Help with automatic installation
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(
" "
)}".`
);
// Ask if you want to install
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();
// Whether to input yes
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;
}
// Start installation
const packageName = "webpack-cli";
console.log(
`Installing '${packageName}' (running '${packageManager} ${installOptions.join(
" "
)} ${packageName}')...`
);
// Execute the installation command
runCommand(packageManager, installOptions.concat(packageName))
.then(() => {
require(packageName); //eslint-disable-line
})
.catch(error => {
console.error(error);
process.exitCode = 1;
});
});
// Installed a , Use it directly
} 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 {
// Two installed , Prompt to delete one before running
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;
}
Four 、 Results after startup
webpack Finally find webpack-cli (webpack-command) This npm package , And perform CLI.
边栏推荐
- Automated test platform (13): interface automation framework and platform comparison, application scenario analysis and design ideas sharing
- Find the original array for the inverse logarithm
- Terminology description in the field of software engineering
- Resttemplate use
- ESP32 - ULP 协处理器在低功耗模式下读片内霍尔传感器HALL SENSOR
- 记一次线上接口慢查询问题排查
- 存储过程学习笔记
- 【微信小程序】如何搭积木式开发?
- Lxml module (data extraction)
- 如果我在广州,到哪里开户比较好?究竟网上开户是否安全么?
猜你喜欢
随机推荐
HW(OD)岗面试题
脏读、幻读和不可重复读
Is it safe to buy funds on Alipay? Where can I buy funds
MySQL data type learning notes
On whether variables are thread safe
产品学习(二)——竞品分析
Router 6/ 以及和Router5 的区别
嵌入式系统
Rclone access web interface
WiFi settings for raspberry Pie 4
Is the account opening of Huafu securities safe and reliable? How to open Huafu securities account
SQL语言的学习记录一
RestTemplate使用
概率论学习笔记
Database notes
Grain Mall - environment (p1-p27)
图解事件坐标screenX、clientX、pageX, offsetX的区别
Docker 安装部署Redis
Jena基于OWL的默认推理查询
给逆序对数求原数组









