当前位置:网站首页>Webapck system foundation
Webapck system foundation
2022-06-29 04:19:00 【HeyCChen】
Why study Webpack
- Understand the front end “ engineering ” Concept 、 Tools 、 The goal is
- Improve personal core competitiveness
- The only way to become a high-level front-end Engineer
What is? Webpack
What constitutes a front-end project ?—— resources

- Before the emergence of front-end engineering tools, resource files were managed manually , Such as through
<link >Label import style file , adopt<script> </script>Tags introduced JS Documents, etc. , But there will be many problems in this way :- The operation process is tedious
- When dependencies exist, they should be written in strict order
- The development is consistent with the production environment, which makes it difficult to access TS perhaps JS New features
- Difficult to access Less、Sass Tools such as
- JS、CSS、 Inconsistent picture resource management models, etc
- In order to solve these problems, many front-end engineering tools have emerged :Webpack、Vite、browserifyjs etc. , To some extent, it is the emergence of these tools , The concept of front-end engineering came into being
- Before the emergence of front-end engineering tools, resource files were managed manually , Such as through
Webpack It is essentially a front-end resource compilation 、 Packaging tools

- Multiple resource files are packaged into one Bundle
- Support Babel、Eslint、TS、CoffeScript、Less、Sass
- Support modular processing css、 Pictures and other resources
- Support HMR + Development server
- Support continuous monitoring 、 Continuous construction
- Support code separation
- Support Tree-shaking
- Support Sourcemap etc.
Webpack Usage of
install Webpack:
npm i -D webpack webpack-cliEdit profile webpack.config.js
// webpack.config.js module.exports = { entry: './src/index.js', output: { filename: "[name].js", path: path.join(__dirname,"./dist"), }, module: { rules: [{ test: /\.less$/i, use: ['style-loader','css-loader','less-loader'] }], } }Execute compile command :
npx webpackIt will be in the root directory dist Folder to get the compiled package file main.js( The default is main.js, You can modify )The core processes ( Extremely simplified version ): Inlet handling 、 Dependency resolution 、 Resource analysis 、 Merge and package resources

Webpack What is essentially done : modularization + Uniformity
- Multiple file resources are merged into one , Reduce HTTP Number of requests
- Support modular development
- Support typescript、CoffeeScript Language
- Unified picture 、CSS、 Processing model of fonts and other resources
Use Webpack
- About Webpack How to use , Basically all around “ To configure ” an , It can be divided into two categories :
- Process class : Act on one or more links in the process , Configuration items that directly affect the packaging effect

- Tool class : Out of the mainstream , Configuration items that provide more engineering capabilities

- Webpack The properties in are used by frequency :
- entry / output
- module / plugins
- mode
- watch / devServer / devtool
- Process class : Act on one or more links in the process , Configuration items that directly affect the packaging effect
Handle CSS: For example, in JS Introduction in CSS file import './index.css'
install Webpack:
npm i -D webpack webpack-cliInstallation dependency : Required loader:
npm i -D style-loader css-loaderEdit profile webpack.config.js add to
moduleHandle CSS fileconst path = require('path'); module.exports = { entry: './src/index.js', output: { filename: "[name].js", path: path.join(__dirname, "./dist"), }, module: { rules: [{ // test: /\.less$/i, test: /\.css$/, use: ['style-loader', 'css-loader'] }], }, mode: 'development', }Terminal use
npx webpackCompile
Use Webpack Handle JavaScript: Access Babel Will be higher version JS Code translated to a lower version JS Code
Installation dependency :
npm i -D @babel/core @babel/preset-env babel-loaderEdit profile webpack.config.js
const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: "[name].js", path: path.join(__dirname, "./dist"), }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.js$/, use: [{ loader: 'babel-loader', options: { presets: [ ['@babel/preset-env'] ], }, }], }, ], }, mode: 'development', }Terminal use
npx webpackCompile
Use Webpack Handle HTML: Don't use loader But use HTML plug-in unit
Installation dependency
npm i -D html-webpack-pluginEdit profile webpack.config.js
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: "[name].js", path: path.join(__dirname, "./dist"), }, module: { rules: [ { // test: /\.less$/i, test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.js$/, use: [{ loader: 'babel-loader', options: { presets: [ ['@babel/preset-env'] ], }, }], }, ], }, plugins: [new HtmlWebpackPlugin], mode: 'development', }Terminal use
npx webpackCompile
Use Webpack Update the thermal module (HMR,Hot Module Replacement)
- The code written can be updated to the browser immediately , And you don't have to refresh the browser
- Edit profile webpack.config.js add to
devServerattributemodule.exports = { //... devServer: { hot: true, }, } - start-up Webpack Use
npx webpack servecommand
Use Webpack Conduct Tree-Shaking, Used to delete dead code
- dead code: The code is not used or unreachable 、 The execution result of the code will not be used 、 The code is read-only and not written …
- Turn on Tree-Shaking:
mode: "production"optimization: {usedExports: true}module.exports = { //... mode: "production", optimization: { usedExports: true, }, }Terminal use
npx webpackCompile
Loader Components
Loader Its function is to transform the content of resources ,Webpack Know only JS,Loader Used to deal with non-standard JS resources , Translation as standard JS
Use Loader( To deal with less File as an example ):
install Loader:
npm i -D css-loader style-loader less-loaderadd to
moduleHandle css file , among less-loader Realized less -> css Transformation ;css-loader take CSS Packaged like module.exports = “${css}” The content of , The contents of the package conform to JavaScript grammar ;style-loader take CSS Modules are packaged into require sentence , And call... At run time injectStyle Function to inject content into the style label . And these three loader It is also loaded in a chain call mode
module.exports = { //... module: { rules: { test: /\.less$/i, use: ["css-loader","style-loader","less-loader"], }, }, }
Loader Characteristics of :
- Chain execution ( Previous loader The output of may be another loader The input of )
- Support asynchronous execution
- It is divided into normal and pitch Two modes
To write Loader
- One with no function loader:
module.exports = function(source, sourceMap?, data?){ //source yes loader The input of may also be the previous loader Output return source; };- stay webpack Call this loader:
module.exports = { //... module: { rules: [ { test: /\.js$/, use: [path.join(__dirname, './loader')] }, ], }, }Commonly used Loader

Plugin Components
Webpack Many functions are implemented by plug-ins
Many well-known tools like VS Code、Webstorm And so on ,Webpack Many of its functions are implemented based on plug-ins
There are many disadvantages if you do not use plug-ins :
- Newcomers need to understand the details of the whole process , High start-up cost and high function iteration cost , Pull a body
- Rigid function , Lack of growth as an open source project
- That is, the mental cost is high 、 Low maintainability 、 Weak vitality
The essence of plug-in architecture : Open to expansion 、 Closed to modification
Use of plug-ins :
- for example
npm i -D webpack-dashboard - Introduce and use plug-ins :
// import the plugin const DashBoardPlugin = require("webpack-dashboard"); // add it to your webpack configuration plugins module.exports = { // ... plugins : [new DashBoardPlugin()], // ... };- for example
Write a plug-in
- Plug ins surround ‘ hook ’ an , The function of a hook is to trigger a hook at a certain stage of compilation , To some extent, it can be understood as an event
class SomePlugin { apply(compiler){ compiler.hooks.thisCompilation.tap('SomePlugin', (compilation) => {}) } }- The core information of the hook :
- opportunity : Specific nodes of the compilation process ,Webpack It will notify the plug-in of what is happening at the moment in the form of a hook
- Context : adopt tapable Provided callback mechanism , Pass context information as a parameter
- Interaction : A lot of existence is attached to the context parameter object side effect The interface of , Plug ins can be changed through these interfaces

- opportunity :compier.hooks.compilation
- Parameters :compilation etc.
- Interaction :dependencyFactories.set
How to learn Webpack


边栏推荐
- C language -- branch structure
- Analysis on the types of source code anti leakage technology
- My creation anniversary
- sql两列变为多行过滤显示
- Here comes Wi Fi 7. How strong is it?
- 快速开发项目-VScode插件
- NotImplementedError: Could not run torchvision::nms
- Redis cache penetration, cache breakdown, cache avalanche
- Cucumber test practice
- Anaconda自带的Spyder编辑器启动报错问题
猜你喜欢

Technology: how to design zkvm circuit

Libuv library overview and comparison of libevent, libev and libuv (Reprint)

If I hadn't talked to Ali P7, I wouldn't know I was a mallet

Blue Bridge Cup ruler method

Rapid development project -vscode plug-in

Why are you a test / development programmer? Can you recall

How sqlserver queries and removes results with null fields in the whole column

Baidu AI Cloud service grid product CSM release 𞓜 hot public beta

开发者方案 · 环境监测设备(小熊派物联网开发板)接入涂鸦IoT开发平台

MySQL column to row conversion without Union
随机推荐
Why are you a test / development programmer? Can you recall
1015 theory of virtue and talent
The five levels of making money, which level are you on?
On June 27, 2022, I have the right to choose the journey of the summer vacation.
Error accessing database
How to create robots Txt file?
【C语言】开启一个线程
树莓派用VNC Viewer方式远程连接
If you choose the right school, you can enter Huawei as a junior college. I wish I had known
Anaconda's own Spyder editor starts with an error
[C language] address of stack memory associated with local variable 'num' returned
LabVIEW displays Unicode characters
1017 a divided by B
1019 digital black hole
Redis 缓存穿透、缓存击穿、缓存雪崩
Implementation of b+ tree index based on xlsx
从零到一,教你搭建「以文搜图」搜索服务(一)
iNFTnews | 元宇宙技术将带来全新的购物体验
Libuv library overview and comparison of libevent, libev and libuv (Reprint)
The people's Bank of China printed and distributed the notice on supporting cross-border RMB settlement of new foreign trade formats