Writing is not easy, without the permission of the author forbid to reprint in any form! If you think the article is good, welcome to follow, like and share!
First introduction to Webpack
At the beginning of Webpack experience
What problems are solved with Webpack
- modular
- Advanced features, development efficiency, security
- ES6+, Typescript, sass, less
- Monitor file changes and reflect them on the browser to improve development efficiency
- Post-development packaging, compression, merging, tree-shaking, and other related optimizations
What is the Webpack
-
Webpck is a static modular packaging tool for modern JS applications
-
Let’s break down the above explanation:
- Bundler: WebPack helps with packaging, so it’s a packaging tool.
- Static: The reason for this statement is that we can eventually package the code as the ultimate static resource (deployed to a static server)
- Modular Module: WebPack supports all kinds of modular development by default, ES Module, CommonJS, AMD, etc
- Modern: The emergence and development of WebPack is the result of the various problems faced by modern front-end development
Webpack and Vite
Will Webpack be replaced by Vite?
- Vite has indeed caused a lot of response, there are also a lot of people optimistic about the development of Vite
- But vite is still a long way from replacing Webpack
- Vue projects currently support the use of Vite as well as WebPack
- The final packing process of vite still needs to be completed by rollup
- The core idea of Vite is not original
- In fact, Vite’s thinking overlaps with that of snowpack, and snowpack is much more mature than it is now
- Of course, in the future vite could surpass Snowpack
- Update iteration of Webpack
- In the development of the project, Webpack will continue to improve itself, using some of the advantages and ideas of other tools
- In so many years of development, both its own advantages and ecology are very strong.
Thoughts on Vite
-
To learn anything, it is important to learn the core ideas
- JS learning TS doesn’t start at zero
- React doesn’t start at 0
-
The emergence of any tool is to better serve our development
-
Whether it is the advent of Vite, or the emergence of new tools in the future, do not have any thoughts of exclusion;
-
We need to understand that tools are there to serve us better
-
There’s no way that there’s a tool that makes us less productive and that tool can become very popular. There’s no such thing
-
Webpack is packaged by default
-
We can package through WebPack and then run the packaged code
-
Execute the webpack command directly in the directory
webpack
-
Executing webpack directly on the terminal may differ between the native installed version and the project version, so define commands in package.json such as “build”:”webpack”, which will be packaged according to the webpack version in package.json (provided install is installed).
-
-
Create a dist folder that holds a main.js file, which is the packaged file
- The code in this file is compressed and uglified
- I don’t care how he does it, but I’ll talk about it later when I talk about how WebPack implements modularity.
- In addition, we still find ES6 syntax in the code, such as arrow functions, const, etc. This is because by default, WebPack does not know whether we need to convert the packaged file to the pre-ES5 syntax. Later we need to use Babel to convert and set it.
-
It is found that it can be packaged normally, but there is a question, how does webpack enter correctly?
- In fact, when we run Webpack, webpack looks for SRC /index.js in the current directory as an entry point
- So, if there is no SRC /index.js in the current project, an error will be reported
-
It is also possible to specify the entry and exit via configuration, for example (usually writing configuration files)
npx webpack --entry ./src/main.js --output-path ./build
Webpack configuration file
-
Often, the projects webPack needs to package are very complex, and we need a series of configurations to meet the requirements, the default configuration is not necessarily possible.
-
We can create a webpack.config.js file in the root directory as a webPack configuration file, for example
const path = require("path");
module.exports = {
entry: "./src/main.js".output: {
filename: "bundle.js".path: path.resolve(__dirname, "build"),}};Copy the code
-
Continue with the webpack command and you can still pack normally
-
Alternatively, instead of using webpack.config.js as the file name, use the command to define the path and file name, for example
-
webpack --config ./wk.congfig.js
Webpack dependency graph
How exactly does WebPack package our project?
-
In fact, when WebPack is working with an application, it will find the entry file based on the command or configuration file;
-
Starting with the entry, a dependency diagram is generated that contains all the modules needed in the application (such as JS files, CSS files, fonts, and so on)
-
Then iterate through the structure of the diagram and package each module (parse using different loaders depending on the file)
Mode configures
-
The Mode configuration option, which tells Webpack to use the built-in optimization for response Mode:
-
The default is production(if nothing is set);
-
Optional values are: ‘none’ | ‘development’ | ‘production’.
-
What’s the difference between these choices?
The Mode configuration represents more configuration
- Green options = all red options
Webpack core process
The core principle of Webpack is thoroughly understood by the article quoted in [10,000-word summary]
The core of this process has completed the two functions of content conversion and resource merger, and the realization includes three stages:
-
Initialization phase:
- Initialization parameters: read from the configuration file, configuration object, and Shell parameters, and obtain the final parameters together with the default configurations
- Create the Compiler object: Create the Compiler object using the parameters obtained in the previous step
- Initialize the build environment: this includes injecting built-in plug-ins, registering various module factories, initializing RuleSet collections, loading configured plug-ins, and so on
- Start compiling: Execute the run method of the Compiler object
- Determine the entry: find all the entry files according to the entry in the configuration, and call compilition.addEntry to convert the entry files to dependence objects
-
Construction phase:
- Make: Module object was created according to the dependence of entry, loader was called to translate the module into standard JS content, JS interpreter was called to convert the content into AST object, and the module that the module depended on was found. Repeat this step until all entry dependent files have been processed by this step
- Complete module compilation: after the last step of recursive processing of all accessible modules, we get the translated content of each module and the dependency diagram between them
-
Generation stage:
- Output resource (SEAL) : Assembles chunks containing multiple modules based on the dependencies between entries and modules, converts each Chunk into a separate file and adds it to the output list. This step is the last chance to modify the output content
- Write to a file system (emitAssets) : After determining the output content, determine the output path and file name based on the configuration, and write the output content to the file system
The single build process is carried out from top to bottom, and details will be discussed below. Before that, for those unfamiliar with the various technical terms mentioned above, please take a look at the introduction:
-
Entry: Compilation Entry, the starting point for webPack compilation
-
Compiler: Compiler manager. After Webpack starts, Compiler objects are created and live until the Compiler exits
-
Compilation: A manager for a single edit process, such as Watch = true, that runs with only one compiler but creates a new Compilation object each time a file change triggers a recompilation
-
Dependence: dependency objects. Webpack records module dependencies based on this type
-
Module: All resources within webpack will exist in the form of “Module” objects, and all operations, translations and merges of resources are based on “Module”
-
Chunk: When compiled and ready for output, Webpack organizes modules into chunks according to specific rules. These chunks correspond to the final output to some extent
-
Loader: A resource content converter that converts content FROM A to B
-
Plugin: Events are broadcast at specific times during webPack construction, and plug-ins listen for these events and intervene in the compilation process at specific points in time
The WebPack compilation process is built around these key objects. For more complete information, see the WebPack Knowledge Graph.
Webpack and Gulp
-
The core concept of Gulp is Task Runner
- You can define your own set of tasks and wait for them to be executed;
- Build flow based on file Stream; P We can use gulp’s plug-in architecture to accomplish certain tasks;
-
The core concept of WebPack is that Module Bundler pWebPack is a modular packaging tool.
- You can use a variety of loaders to load different modules;
- You can use a variety of plug-ins to accomplish other tasks in the WebPack lifecycle;
-
Advantages and disadvantages of Gulp compared to Webpack:
- Compared with Webpack, gulp is more simple and easy to use. It is more suitable for writing some automatic tasks.
- However, gulp is not currently used for large projects (Vue, React, Angular). For example, gulp does not support modularity by default.
Quality articles recommended:
- [10,000 words summary] One article thoroughly understand the core principle of Webpack
- Webpack plug-in architecture in-depth explanation
- 10 minutes introduction to Webpack: module.issuer properties
- Dependency Graph: Dependency Graph (Dependency Graph
- Share several Webpack utility analysis tools
- Share a Webpack knowledge graph
Nuggets: Front-end LeBron
Zhihu: Front-end LeBron
- Continue to share technical blog posts, follow the wechat official account 👇🏻