Literacy: Webpack from literacy to handwriting (part 1)

Brother Lu, as a front-end beginner, can you literate webpack? After all, this thing is rarely used in school projects, so I really want to know about it.

Speaking of webpack, Xiaolu will specialize in a series, from simple literacy to hand-painting. This is a process. As long as you can work hard, you can hand-paint the source code with Brother Lu.

This article mainly focuses on literacy. After all, most of them are students, so I know webpack and what can help us do in the future, how to get a promotion and salary increase through webpack, haha, it is a bit big, this is not to tout webpack. Let's go directly to the topic.

The full text is explained in vernacular, and it is guaranteed that you will understand everything you say.

From acquaintance to encounter

I learned the front-end in the early stage, and I didn’t know there was such a thing. The first time I heard the term webpack was just 2 months after switching to the front-end, WC! Isn't the front-end just a web design, and this fancy thing, I asked my classmates later, I didn't know what this stuff was doing.

Literacy: Webpack from literacy to handwriting (part 1)

Later, I searched a lot of related information on the Internet, but due to cognitive limitations, I couldn't figure out what it was used for.

In this way, until later, until the front-end engineering is mentioned, I fully understand what webpack can do and silently play a powerful role in the front-end. In this era of front-end engineering, webpack is a powerful tool for front-end projects.

Why use webpack?

With the growing of front-end projects, a large number of resource files and codes have to be compressed, making the packaged project smaller and lighter.

Then webpack appeared, and the emergence of webpack is to solve these problems. If you merge and compress files, you only need to configure webpack in the project and execute the relevant commands to compress and merge the project.

Literacy: Webpack from literacy to handwriting (part 1)

In addition, there are other functions, such as hot update, every time we change the project, we need to refresh the web page, and after using webpack, the page refreshes automatically after the project is saved.

Pre-processors such as Scss and Less have been added, as well as style processing, such as automatically adding browser prefixes to attributes, and using babel to convert higher grammars such as ES6 and ES7 that do not support browsers into ES5 grammar recognized by the browser.

Through webpack, we can increase our development efficiency, and use webpack's internal packaging mechanism to automatically process some things. Development efficiency is to save time, and the project can be efficiently maintained, thereby reducing some costs.

What is webpack?

In a word, webpack is a packer that packs all scripts, pictures, resources, styles, etc.

Literacy: Webpack from literacy to handwriting (part 1)

Introduction to webpack configuration

To be honest, this thing is easy to use in the project, but it is very unfriendly to beginners. At the very least, for me when I just started learning, it will be easy to see, and it will be awkward.

Besides, it's not that I complained about the official Chinese documents of webpack. For beginners, especially those who have a poor understanding of concepts, the early learning is extremely unfriendly. Originally webpack is not that difficult to understand, but these things add some mystery to webpack.

In addition, after gradually researching the webpack source code, I found that the other reasons for the unfriendly to beginners in the early stage are that some concepts and some configurations, etc., know it and don't know why. After reading the source code, I know how these configurations are used.

basic concept

1. Entry and exit

Packed files must have a total entry path, erntry is the attribute of entry file path configuration. At the same time, it corresponds to the output path, that is, the path to which the packaged file should be placed, and what is the name of the packaged file.

Entry can also configure multiple entry files, package these files separately, and then configure multiple exits, different packaged files, and put them in different folders.


1const path = require("path")
2module.exports = {
3  mode: "development", // 生产模式
4  entry: "./src/js/index.js", // 入口
5  output: {
6    path: __dirname + "/dist/pro", // 向出口
7    filename: "xiaolu.min.js"     // 输出的文件名
8  },
9}

I put the main configuration methods on github, which can be viewed by reading the original text.

2、loader

We can understand it as a loader. We can set up different loader to convert the code of different files. For example, we have configured the css-loader loader, which is mainly used to parse the files imported by the import syntax encountered in the code. Another example is the configuration style-loader is mainly used to automatically import the packaged files into the index.html file.

It can be said that after configuring the loader, the rest is fully automated. The loader executes the matching from bottom to top, from right to left, and the order must be paid attention to.


 1module: {
 2    rules: [
 3      //-> CSS 样式处理
 4      {
 5        test: /\.css$/,
 6        use: [
 7          // 从后向前加载
 9          "style-loader",
10          "css-loader"
11        ]
12      },
13    ]
14  },

At the same time, we can also customize the loader, that is, according to the additional needs of our project, we can write a loader that meets the needs. This is often asked in interviews, have you ever written loader by hand?

3. Plugins

Plugins mainly introduce third-party plugins. Some commonly used plugins have been implemented for us. We only need to download and install the configuration in npm.

For example, the htmlWebpackPlugin plug-in is mainly used to package html templates, and then you can configure some options to write the html code in one line or delete the double quotes.


 1plugins: [
 2    new HtmlWebpackPlugin({
 3      filename: "index.html",
 4      template: "./src/html/demo.html",
 5      minify: {
 6        removeAttributeQuotes: true, // 删除双引号
 7        collapseWhitespace: true // 将其折叠为一行
 8      }
 9    }),
10]

After the above is packaged, the html will become a line of code, thus saving the file size.

The most basic and important configurations are these three. What plug-ins do you want to use? According to the official website or the commonly used projects in the github summary, there is basically no problem getting started with webpack.

webpack optimization

In addition, webpack has another biggest use for front-end performance optimization.

For example, debugging projects, speeding up packaging, and enabling multi-threaded packaging, and extracting common code, lazy loading, and hot update are all optimization methods commonly used in projects.

For example, multi-threaded packaging. Webpack itself is single-threaded. If the project is large enough, the packaging speed must be very slow. In addition to my bad computer, it takes several minutes. If multi-threading is enabled, multiple project files will be opened. The threads are packed, and the speed is whistling.


 1rules:[
 2    {
 3        test: /\.js$/,
 4        exclude:/node_modules/,
 5        include: path.resolve('src'),
 6        use: 'Happypack/loader?id=js'   // 使用 happypack 的 loader 进行打包
 7    }, 
 8    {
 9         test: /\.css$/,
10        // ......
11    }
12]
13
14plugins:[
15    //css
16    new  Happypack({
17      id:'css',
18    }),
19    // js
20    new Happypack({
21     id:'js',
22     use:[{                                // 插件配置
23            loader: 'babel-loader',         
24            options: {
25                presets:[
26                    '@babel/preset-env'  
27                ]
28            }
29        }]
30    })
31})

Webpack also plays a key role in the optimization of front-end performance. Not only can this thing be used, but it must also be understood in order to be flexible in actual projects.

to sum up

Today's article is mainly an introductory literacy for webpack. After all, for beginners who are new to webpack, it is necessary to understand some concepts. With these basic concepts, it is easy to get started.

I’m here for literacy today. If there are any shortcomings in the article, you can leave a message to add, and then take the time to continue sharing a webpack to see how its internal implementation principle is.

Guess you like

Origin blog.51cto.com/15064450/2599790