当前位置:网站首页>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.
边栏推荐
- 问题:OfficeException: failed to start and connect(二)
- Using fuseki query when there are multiple models in TDB
- rclone中文文档:常用命令大全
- 启牛学堂合作的证券公司是哪家?开户安全吗?
- PAT (Advanced Level) Practice 1057 Stack
- SQL statement
- Product learning (III) - demand list
- [wechat applet] how to build a building block development?
- Design of sales management system for C language course (big homework)
- Promise
猜你喜欢

如何通过cdn方式使用阿里巴巴矢量图字体文件

Product learning (III) - demand list

产品学习(一)——结构图

Insufficient free space after clearing expired cache entries - consider increasing the maximum cache space
![[wechat applet low code development] second, resolve the code composition of the applet in practice](/img/ab/28ab01db84b1437220e659118b2871.png)
[wechat applet low code development] second, resolve the code composition of the applet in practice

Async and await

How to use Alibaba vector font files through CDN

sci-hub如何使用

Problem: officeexception: failed to start and connect (II)

【计网】(一) 集线器、网桥、交换机、路由器等概念
随机推荐
ESP32深度睡眠电流怎样低于10uA
Terminology description in the field of software engineering
解决The code generator has deoptimised the styling of xxxx.js as it exceeds the max of 500kb
WiFi settings for raspberry Pie 4
谷粒商城-环境(p1-p27)
Interview questions for HW (OD) post
Understand esp32 sleep mode and its power consumption
mysql数据类型学习笔记
DML statement in SQL (data operation language)
RestTemplate使用
解决无法读取META-INF.services里面定义的类
Stored procedure learning notes
8 figures | analyze Eureka's first synchronization registry
微信公众号内嵌跳转微信小程序方案总结
软件工程领域的名词描述
rclone 访问web界面
JSON module
(I) apple has open source, but so what?
Router 6/ 以及和Router5 的区别
Is fixed investment fund a high-risk product?