An in-depth introduction to webpack principles (with examples)
This article is copied from "Webpack Explained in a Simple and Simple Language". It is recommended that those who want to learn the principles type it once, operate it once, and explain it to others once, and then they will know it.
I hope you have it before reading. Practical experience related to webpack, otherwise you will not understand it after reading it
It takes a few minutes to read this article, and it takes a long time to understand it by yourself
0 Configuration file
First take a brief look at the webpack configuration file (webpack.config.js):
var path = require('path'); var node_modules = path.resolve(__dirname, 'node_modules'); var pathToReact = path.resolve(node_modules, 'react/dist/react.min.js'); module.exports = { // 入口文件,是模块构建的起点,同时每一个入口文件对应最后生成的一个 chunk。 entry: { bundle: [ 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8080', path.resolve(__dirname, 'app/app.js') ] }, // 文件路径指向(可加快打包过程)。 resolve: { alias: { 'react': pathToReact } }, // 生成文件,是模块构建的终点,包括输出文件与输出路径。 output: { path: path.resolve(__dirname, 'build'), filename: '[name].js' }, // 这里配置了处理各模块的 loader ,包括 css 预处理 loader ,es6 编译 loader,图片处理 loader。 module: { loaders: [ { test: /\.js$/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ], noParse: [pathToReact] }, // webpack 各插件对象,在 webpack 的事件流中执行对应的方法。 plugins: [ new webpack.HotModuleReplacementPlugin() ] };
1. Overview of working principle
1.1 Basic concepts
Before understanding the principles of webpack, you need to master the following core concepts
Entry: Entry, the first step of webpack construction starts from entry
module: module, in webpack a module corresponds to a file. webpack will start from entry and recursively find all dependent modules
Chunk: code block, a chunk is composed of multiple modules, used for code merging and splitting
Loader: Module converter, used to convert the original content of the module into new content as required
Plugin: Expansion plug-in, in the webpack build process Corresponding events will be broadcast at specific times, and plug-ins can monitor the occurrence of these events and do corresponding things at specific times
graph TD 初始化参数 --> 开始编译 开始编译 -->确定入口 确定入口 --> 编译模块 编译模块 --> 完成编译模块 完成编译模块 --> 输出资源 输出资源 --> 输出完成
- Initialization parameters: read from the configuration file (default webpack.config.js) and shell statements Get and merge the parameters to get the final parameters
- Start compilation (compile): Initialize the Comiler object with the parameters obtained in the previous step, load all configured plug-ins, and execute the run method of the object Start compiling
- Determine the entry: Find all entry files according to the entry in the configuration
- Compile module: Starting from the entry file, call All configured Loaders translate the module, then find out the modules that the module depends on, and then recurse this step until all the entry-dependent files have been processed
- Complete the compilation module: after the fourth After this step, the final translated content of each module and the dependencies between them are obtained.
- Output resources: According to the dependencies between the entry and the modules, they are assembled into individual modules. Contains chunks of multiple modules, and then converts each chunk into a separate file and adds it to the output list. This is the last chance to modify the output content
- Output is completed: After confirmation After outputting the content, determine the output path and file name according to the configuration (webpack.config.js && shell), and write the content of the file into the file system (fs)
## The #webpack build process can be divided into the following three stages.
- Initialization: start the build, read and merge configuration parameters, load plugin, instantiate Compiler
- Compilation: starting from Entry, for each Each Module serially calls the corresponding Loader to translate the content in the file, then finds the Module that the Module depends on, and compiles it recursively.
- Output: Combine the compiled Modules into Chunks , Convert the Chunk into a file and output it to the file system
- If it is executed only once, the process is as above, but when the listening mode is turned on, the process is as follows
graph TD 初始化-->编译; 编译-->输出; 输出-->文本发生变化 文本发生变化-->编译
1.3 .1 Initialization phase
The events that will occur during the initialization phase are as follows
Description | |
---|---|
Read and merge parameters from the configuration file and shell statements to obtain the final parameters. This process will also execute the plug-in instantiation statement new in the configuration file. Plugin() | |
Instantiate Compiler and pass in the parameters obtained in the previous step. Compiler is responsible for file monitoring and starting compilation. The Compiler instance contains the complete webpack configuration, and there is only one Compiler instance globally. | |
Call the plug-in's apply method in sequence so that the plug-in can monitor all subsequent event nodes. At the same time, pass a reference to the compiler instance into the plug-in to facilitate the plug-in to call webpack's api through the compiler | |
Start applying the Node.js style file system to the compiler Object to facilitate subsequent file search and reading | |
Read the configured Entrys and instantiate a corresponding EntryPlugin for each Entry. Prepare for the recursive parsing of the Entry later | |
Calling the apply method of all built-in and configured plug-ins | |
Initialize the resolver according to the configuration. The resolver is responsible for finding the file with the specified path in the file system |
##Event | Explanation |
---|---|
#run | Start compilation once |
Watch-run | Start compilation in monitor mode, the file occurs Changes will recompile |
compile | Tell the plug-in that a new compilation is about to start, and at the same time bring the compiler object to the plug-in |
compilation | When webpack is running in development mode, a new compilation is created every time a change to a file is detected. A Compilation object contains the current module resources, compiled resources, changed files, etc. The compilation object also provides a lot of event callbacks for plug-ins to expand |
make | After a new compilation object is created, the file will be read from entry. According to the file type Compile the file with the compiled loader. After compilation, find the files that the file depends on, compile and parse recursively |
after-compile | One compilation execution is completed |
invalid | When an error is encountered, a change event will be triggered. This event will not cause webpack to exit |
Explanation | |
---|---|
Use the corresponding Loader to convert a module | |
After using the loader to convert a module Finally, use acorn to parse the converted content and output the corresponding abstract syntax tree (AST) to facilitate webpack to analyze the code | |
From the configured entry The module starts and its AST is analyzed. When it encounters require statements that import other modules, it is added to the list of dependent modules. At the same time, the newly found modules are recursively analyzed to finally figure out the dependencies of all modules | |
All modules and dependent modules are converted through Loader, and Chunks are generated based on dependencies | |
Explanation | |
---|---|
All files that need to be output have been generated, ask the plug-in Which files need to be output and which do not need to be output | |
After determining which files to output, execute file output, == can be obtained and modified here Output content== | |
File output completed | |
Completed successfully A complete compilation and output process | |
If an error occurs during compilation and output, causing webpack to exit, it will jump directly to this step. The plug-in can Get the specific error reason in this event |
The above is the detailed content of An in-depth introduction to webpack principles (with examples). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
