The definition of a webpack
Webpack is essentially a packer, a tool for modularizing front-end files.
As can be seen from the figure, the developer changed the files with various suffixes under development into JS, PNG and CSS files after webpack. In front end engineering today, if you say you don’t use Webpack, you’re embarrassed to leave the house.
What are the main features of WebPack?
-
As a module packaging tool, Webpack itself can solve the problem of modular code packaging, packaging scattered JavaScript code into a JS file.
-
For code with environmental compatibility problems, Webpack can compile and transform it through the Loader mechanism during the packaging process, and then package it.
-
Webpack supports loading any type of resource file in JavaScript in a modular manner for different types of front-end module types. For example, we can load CSS files in JavaScript through Webpack. The loaded CSS file will work with the style tag.
In addition, Webpack also has the ability to break up the code, so that all the modules in the application can be packaged in pieces according to our needs. This way, you don’t have to worry about packing all the code together, resulting in a single file that is too large and slow to load. We can package together the modules necessary for the initial application loading, and package the other modules separately. When a module is actually needed in the application working process, the module can be loaded asynchronously to achieve incremental loading, or incremental loading, which is very suitable for large modern Web applications.
Core elements of webpack (Entry, Output, Loader, and Plugin)
So let’s do a little demo to see how webPack works in its simplest form.
├─ ├─ SRC │ ├─ design.html │ ├─ ├─ ├─ design.css │ ├─ ├─ ├─ ├─ ├.css │ ├─ ├─ ├.css │ ├─ ├─ ├─ ├─ ├─ ├─ ├.css │ ├─ ├─ ├─ ├─ ├─ ├─ ├─ ├── webpack.config.jsCopy the code
// ./webpack.config.js
// All configuration is in this object
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const webpack = require('webpack');
module.export = {
entry: './src/main.js'.output: {
filename: 'bundle.js'.path: path.join(__dirname, 'dist')},module: {
rules: [{test: /\.css$/.// Whether to use this loader based on the file path match encountered during packaging
use: [
'style-loader'.'css-loader'
] // Specify a specific loader}},plugins: [new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
title: 'Webpack Plugin Sample'.template: './index.html'}})],Copy the code
In this, we can see the basic configuration when WebPack is packaged.
- Entry: Entry file of the Webpack
- Output: Output file packed by webpack
- Loader (which is the content of the Moduls package)
- Plugins (Plugins for WebPack)
Loader and plugins are explained here
Loader:
Loader is the soul of Webpack as a packer. Before loader, Webpack was a young man who could only recognize JS files. When he came across CSS, PNG and other special resources, he could only blink and tell the developer in the command line: “I don’t know this thing!” . Therefore, Webpack has loader as a helper. Loader can help WebPack to convert these file types into JS files when it encounters those file types that WebPack does not recognize.
How does loader work? Take CSS as an example:
-
First, use NPM to follow the corresponding loader file, CSS-loader;
-
Add a Rules array to the Module property of the configuration object. This array is our load rule configuration for the resource module, where each rule object requires two properties:
The first is the test property, which is a regular expression that matches the path of the file encountered during packaging. Here we end with.css;
Then there is the use attribute, which specifies the loader to use for the matched file, in this case CSS-loader.
-
After the configuration is complete, we go back to the command line terminal and run the packaging command again. There will be no errors in the packaging process, because the CSS file will be handed to CSS-Loader and then packaged by Webpack.
It is also important to note that CSS-loader only loads the CSS module into the JS code, but does not use the module. Therefore, we also need to use a style-loader on the basis of CSS-loader to append the result of CSS-loader conversion to the page through the style label. Loaders are executed from right to left and from bottom to top.
Plugins:
If loader is the soul of Webpack, plugins are equivalent to adding imaginary wings to Webpack, horizontally expanding the construction ability of Webpack, and adding to the efficiency of developers.
Here are a few of the most common application scenarios for plug-ins:
- Implement automatic cleanup of the dist directory before packaging (last packaging result)
- Automatic generation of application required HTML files;
- Inject potentially variable parts of the code, such as API addresses, depending on the environment;
- Copy resource files that you do not need to participate in packaging to the output directory.
- Compress the output of Webpack after it is packaged;
- Automatically publish packaged results to the server for automatic deployment.
In short, Webpack with Plugin can do almost anything. Plugins make it easy to implement most of the features often used in front-end engineering, which is why many new webPack students think “WebPack is front-end engineering, or front-end engineering is Webpack”.
So, how does WebPack implement these plug-ins? In fact, it is very simple to say that the plug-in mechanism of Webpack is the most common hook mechanism in software development.
The hook mechanism is also particularly easy to understand, somewhat similar to events on the Web. There are many links in Webpack, and in order to facilitate the extension of plug-ins, Webpack almost buried a hook in each link. This allows us to easily extend the capabilities of Webpack by mounting different tasks on these different nodes as we develop the plug-in.
For details about the predefined hooks, we can refer to the API documentation:
- Compiler Hooks
- Compilation Hooks
- JavascriptParser Hooks
Webpack helps increase productivity
Webpack Dev Server
Now everyone in the front-end development, should be able to feel the convenience of development now. As long as the virtual server of the project is started, after the developers modify the code, the corresponding page will modify the corresponding page, and the developers can check whether their requirements have been realized in the code in real time. In fact, these functions, in the use of Webpack engineering, are webpack devServer attributes to achieve.
#Webpack - dev - server installation
$ npm install webpack-dev-server --save-dev
#Run webpack - dev - server
$ npx webpack-dev-server
Copy the code
// ./webpack.config.js
const path = require('path')
module.exports = {
// ...
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true.port: 9000
// ...
Detailed configuration document: / / https://webpack.js.org/configuration/dev-server/}}Copy the code
When we run webpack-dev-server, it starts an HTTP server internally, provides static file services for the packaged results, and automatically packages our application with WebPack, then listens for changes to the source code, and immediately repackages the files when they change. The process is as follows:
It is worth noting that devServer runs in memory, and the internal HTTP Server reads these files from memory. This reduces unnecessary disk reads and writes and greatly improves overall build efficiency.
In addition, devServer provides us with a proxy for proxy. When there are too many servers, you will inevitably encounter cross-domain requests based on the same origin policy of the browser. At this point, we might ask the back end to help us add proxies to the server. If this requirement is easy, the back end will do it for you. However, sometimes, maybe because the back-end is busy, or the configuration on the server is not easy to modify, then you can try the front-end proxy to solve some problems.
- A proxy manages a relative address rather than an absolute address. As shown below:
// ./webpack.config.js module.exports = { // ... DevServer: {proxy: {'/test': {target: 'https://abc.com/',// points to the address of the server to request, such as 'https:// 'changeOrigin: // Set onProxyReq to true: Function (proxyReq) {proxyReq. RemoveHeader ('origin')}, False, // HTTPS certificate ignored pathRewrite: {'^/test' : '/'} // this step is also important, because it identifies the target server by '/test', so it needs to change '/test' to/to cancel the effect of test},}}}Copy the code
Once done, open the command line terminal and run webpack-dev-server. And then we open up the browser, and here we just try to request, and we get the data we want. Because this address has been proxied to the data interface of ABC. At this point, we can go back to our code and request the back-end interface using the local same-origin address after the proxy without worrying about cross-domain issues.
Thank you
Thank you for reading this article. I hope it will be helpful to you. If you have any questions, please point out.
I’m a pumpkin (✿◡ ◡), thumbs up if you think it’s ok ❤.