当前位置:网站首页>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.
边栏推荐
猜你喜欢

Async and await

SQL statement

8 张图 | 剖析 Eureka 的首次同步注册表

Code practice - build your own diffusion models / score based generic models from scratch
![[wechat applet] view container and basic content components](/img/25/181986ab4bf048854d1d1ca87de637.jpg)
[wechat applet] view container and basic content components

Product learning (III) - demand list

解决无法读取META-INF.services里面定义的类

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

发现了一个 MySQL 的巨坑:update 更新别再用影响行数做判断了!!!
![[wechat applet] how to build a building block development?](/img/69/edb02c88b52b474a797307b96de369.jpg)
[wechat applet] how to build a building block development?
随机推荐
Introduction to spark (one article is enough)
问题解决:OfficeException: failed to start and connect(一)
Internet worm
[wechat applet] how to build a building block development?
[wechat applet] to solve button, input and image components
Dirty reading, unreal reading and unrepeatable reading
Storage function learning notes
(上)苹果有开源,但又怎样呢?
K8s set up redis cluster
Automated test platform (13): interface automation framework and platform comparison, application scenario analysis and design ideas sharing
Free trial of self-developed software noisecreater1.1
H5网页判断是否安装了某个APP,安装则跳转未安装则下载的方案总结
基金定投是高风险产品吗?
Rclone Chinese document: a collection of common commands
Is it safe to buy funds on Alipay? Where can I buy funds
2022 年江苏省职业院校技能大赛(中职) 网络搭建与应用赛项公开赛卷
Resttemplate use
2022 Jiangsu Vocational College skills competition (secondary vocational school) network construction and application open competition volume
清除过期缓存条目后可用空间仍不足 - 请考虑增加缓存的最大空间
C language course set up salary management system (big homework)