Hello everyone, I’m Xiao CAI. A man who wants to be a man who talks architecture! If you also want to be the person I want to be, or point a concern to do a companion, let small dishes no longer lonely!

This article focuses on using Webpack

Refer to it if necessary

If it is helpful, do not forget the Sunday

Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!

The front-end cognitive

Quite a lot of people on the front-end development is a certain misunderstanding, the feeling will point H5 + C3 + JS is equal to the front-end development, but in recent years the front and back end of the separation of the model gradually popular, it shows that the front-end has not been as simple as before.

Standing in my perspective of the backend, the front end is a civil officer, the back end is a military general, can not be said to be proficient in civil arts and martial arts, but at least for the military at the same time can not be ignorant, back a step or two, the current end internship sister encountered a Bug at a loss when, If you can help her, you are a hero in the eyes of her.

In fact, front-end development consists of the following modules:

  • Modularization (MODULarization of JS, modularization of CSS, and modularization of resources)
  • Componentization (reuse of existing UI structures, styles, and behaviors)
  • Standardization (division of directory structure, standardization of code, standardization of interface, standardization of document, Git branch management)
  • Automation (Automated build, automated deployment, automated testing)

Just like the back end, all modules are available.

In terms of engineering, there are major solutions for back-end development such as Maven and Gradle projects. Front-end engineering solutions are also available with WebPack and Vite. So let’s move on to the main topic of today, Webpack

Webpack

I. Conceptual cognition

Essentially, WebPack is a static module packaging tool for modern JavaScript applications. When WebPack processes an application, it internally builds a dependency graph from one or more entry points and then combines each module you need in your project into one or more bundles, which are static resources that are used to present your content.

The above content is extracted from the official website. Here’s a brief overview

  • Concept summary: Webpack is a concrete solution for front-end project engineering

  • Function summary:

    1. Provides friendly front-end modular development support
    2. It provides powerful functions such as code compression and obfuscation, handling browser-compatible Js, and performance optimization
  • Advantages: improved front-end development efficiency and project maintainability

Two, basic use

Real knowledge comes from practice! We use it directly to reinforce awareness.

First we need to create a blank directory and then execute NPM init -y in the blank directory to initialize the package.json configuration file

Json is equivalent to the Pom.xml file in the Maven project

In Maven projects we usually put the source code in the SRC directory, so the next step is to create the SRC directory in this directory, and then create two files: index.html (home page) and index.js (script file).

Traditionally, we import Jquery files in one of two ways

  • One is to download jquery.mini-js and introduce it into your project
<script src=".. /js/jquery.js"></script>
Copy the code
  • One way is to reference the existing CDN library on the Internet, so that you do not need to download
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Copy the code

Both ways have their advantages and disadvantages, here do not do too much explanation!

Since our project was initialized using NPM, we can use NPM to help us download the packages we need

npm install jquery -s
Copy the code

The package we just downloaded can be seen in package.json. Does this remind you of maven’s install command

After the jquery package is installed, you can view the package in node_modules

Then reference it in your project

The browser checks that the JS is running properly

The above way is also the traditional way to lead the package, and webpack is still nothing to do with. Let’s look at how WebPack is used.

1. Webpack installation

Run the following command from your terminal to install the two packages associated with WebPack:

NPM install [email protected] [email protected] -dCopy the code

extension

  • npm install xxx -S, that is,npm install module_name --saveWrite dependencies
  • npm install xxx -D, that is,npm install module_name --save-devWrite devDependencies

DevDependencies is a package that we need for development. It’s only for the development phase. We don’t need these packages when we go live

Dependencies, which need to be published to production.

2. Webpack configuration

We need to create a webpack configuration file called webpack.config.js in the root directory of the project and initialize the following basic configuration:

module.exports = {
    mode: "development"
}
Copy the code

The mode value is mutable and has two optional values

  • development

1. Suitable for development environment

2. Code compression and performance optimization will not be performed on the files generated by packaging

3, packaging speed is fast, suitable for use in the development stage, can quickly respond to the change of the page

  • production

1, suitable for production environment

2. Code compression and performance optimization will be carried out for the files generated by packaging

3, the packaging speed is slow, only suitable for use in the project release phase

1) The role of configuration files

Webpack.config. js is the webPack configuration file that WebPack reads to package the project based on the given configuration before actually starting to package the build

Webpack is a packaging tool developed based on Node.js, so it supports node.js-related syntax and modules to personalize webpack configuration in its configuration file

Let’s go back to webpack and get back to webpack!

There is a familiar saying in Java: Everything is an object, so in front-end engineering we have the same saying: Everything is a module

We no longer need the traditional js import method:

<script src=".. /node_modules/jquery/dist/jquery.min.js"></script>
Copy the code

We can import jquery where we need it. Is jquery required for index.html? No, the index.js script file does, so we just need to import it in the index.js file

Then we also need to modify the package.json file:

We added the dev script, which can be executed by NPM run under the script node.

Then we run the NPM run dev command on the terminal to start webpack to build the project

Pop, quick! A dist directory is generated in the project directory with the main.js script file

We then import the main.js file in the index. HTML file and look directly at the result, which we right click to open in the browser

What is main.js?

In versions of ** WebPack 4.x and 5.x ** there are the following default conventions:

  • The default package entry file issrc/index.js
  • The default output file path isdist/main.js

The rules are die and people are alive, so we can change the default convention for packaging in webpack.config.js!

Now that we know the convention, so we know that the index.js content is included in main.js, we can look directly at the main.js file and see what we expect

Let’s go back to the previous loadpoint ① and continue with the description of the webpack.config.js configuration file

In the webpack.config.js file, we can specify the entry to the package through the entry node, and then specify the exit to the package through the Output node.

This is what we called breaking the default rule above!

Now that we’ve covered the basics of Using WebPack, let’s take a look at using plug-ins in WebPack

Three, plug-in use

Plug-ins, as the name implies, are used to extend the functions of WebPack. By installing and configuring third-party plug-ins, you can extend the capabilities of WebPack, making it more convenient to use WebPack. The most commonly used Webpacks are two:

  • webpack-dev-server

1. Similar to the Nodemon tool used in node.js

2. Whenever the source code is modified, WebPack automatically packages and builds the project

  • html-webpack-plugin

1. Similar to a template engine

2. You can customize the content in the index.html page by using this plug-in

Let’s start with how to use the first plug-in

1) webpack – dev – server

Webpack-dev-server enables WebPack to listen for changes to the source code of a project for an automatic package build

(1) the installation

Use the following command to install the plug-in in your project

NPM install [email protected] - DCopy the code
(2) configuration

1. Script in package.json needs to be modified

"scripts": {
    "dev": "webpack server"
}
Copy the code

2. Run NPM run dev

You can see a sentence: the project is running at localhost:8080/. The dist directory does not appear after the run

We then go to that address and instead of seeing the page we want, we need to click on the SRC directory

Based on the above results, we may have the following questions:

  • Why it worksnpm run devWill there be an access address?

This is because webpack-dev-server starts a live packaged HTTP server

  • Where is the generated file from the package?

To answer this question, we need to know the difference between configuring and not configuring Webpack-dev-server

1. If webpack-dev-server is not configured, the generated files generated by webpack will be stored on the actual physical disk (according to the path specified by output).

2. In the case of webpack-dev-server configuration, the generated files will be stored in memory, not according to the path specified by the output node. This advantage is that the real-time packaging output is improved, so the memory is much faster than the physical disk

  • How can I access files generated in memory?

By default, files generated in memory are placed in the root directory of the project, but are virtually invisible. We can directly use/to represent the root directory of the project, followed by the name of the file to access, you can access the file in memory.

To close with three questions, let’s move on to the next plug-in, html-webpack-plugin

2) HTML – webpack – the plugin

Webpack -plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin: webpack-plugin

(1) the installation

As always, we need to install it with the following command

NPM install [email protected] - DCopy the code
(2) configuration

(3) to run

Let’s see the result by running NPM run dev

With this plug-in, we can see that the page is already accessible directly from the path ~

Some of you might be asking the question, is it okay if I don’t want to go through port 8080, or even through localhost? The answer is yes, we can configure the Webpack-dev-server plug-in with the devServer node:

devServer: {
    // After the first successful packaging, the browser is automatically opened
    open: true.// In HTTP, the port number 80 can be omitted
    port: 8081.// Specify the address of the running host
    host: '127.0.0.1'
},
Copy the code

Then we run the project and access the page through 127.0.0.1:8081:

So far we have introduced the use of two plugins, next we will look at something different ~!

Iv. Use of Loader

As we said at the beginning, in front-end engineering, everything is modular. So we can import jquery JS files in the index.js script file by importing them. Is it possible to import CSS files as well? Let’s try:

When we want to import the CSS file by import, the console gives us a sentence: you might need an appropriate loader to handle this file type, appropriate? Loader? . What is loader?

In actual development, WebPack can only package modules with.js extensions by default. Webpack can’t handle other modules that don’t end in.js suffix, which is the case above, but how? As the prompt text says, we need to download an appropriate loader to handle this file type.

There are many kinds of loader loaders, but their purpose is to help WebPack process specific file modules

  • css-loader: Can be packaged.cssRelevant documents
  • less-loader: Can be packaged.lessRelevant documents
  • Babel-loader: packages advanced JS syntax that webpack cannot handle

Next we will deal with the problem of CSS guide package encountered above

(1) the installation

Use the following command to install the Laoder that handles CSS files

NPM I [email protected] [email protected] -dCopy the code
(2) configuration

We need to configure the corresponding Loader rules in the webpack.config.js file

module: {
  rules: [
    // Loader to process.css files
    { test: /\.css$/, use: ['style-loader'.'css-loader']},]}Copy the code
(3) to run

Then we run the file and the browser looks at it

The result shows that THE CSS-Loader works. Let’s see how the rule is written:

{ test: /\.css$/, use: ['style-loader'.'css-loader']}Copy the code

Test indicates the matched file type, and use indicates the loader to be invoked

  • The loader order in the use array is fixed
  • multipleloaderThe call order ofCall from back to front

Other loaders need to be installed and configured in the webpack.config.js file

1) less – loader

The installation

NPM I [email protected] [email protected] -dCopy the code

configuration

Module: {rules: [// loader to handle.css files {test: /\.css$/, use: ['style-loader', 'css-loader']}, // loader to handle.less files {test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] }, ] }Copy the code

2) Babel – loader

The installation

NPM I [email protected] @babel/[email protected] @babel/[email protected] -dCopy the code

configuration

Module: {rules: [// loader to handle.css files {test: /\.css$/, use: ['style-loader', 'css-loader']}, // loader to handle.less files {test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader']}, // Loader {test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ } ] }Copy the code

We have seen several loader functions, so what is the processing process? Let’s use a picture to illustrate:

Five, package release

After completing the above project development, we will come to the stage of packaging and release. Everything we have done in front of us must be released in the end, so in order to make the project run in the production environment with high performance, we need to package and release the project.

(1) configuration

Package distribution also needs to be configured. We need to configure it in the script node under package.json file:

With the NPM run build command, we can see the familiar dist directory at the root of the project

If there is no rule configuration specified, by default the packed files will be placed in the dist directory, but if we want to put js files in the JS directory and image files in the image directory, we need to configure them in webpack.config.js

The directory where our JS files are generated has been configured using the Output node

So we also need to configure the output directory of other files, here is an example of the image file:

We also configure it in the webpack.config.js file, but in this case we configure it in the rules node:

At this point we are almost done packaging, but what happens when we change the JS generation directory?

We found that redundant files were generated and did not delete the old files. Should we manually delete them every time we pack? Of course not! To automatically clean up old files in the dist directory every time you pack and publish, you can install and configure the clean-Webpack-plugin

The installation

NPM install [email protected] - DCopy the code

configuration

run

Sixth, the Source of the Map

This Source Map is a little bit interesting because when we go live on the back end, if something goes wrong, we usually go to the server and look at the error log. So if there is a problem in the front end is very convenient, we can directly through F12 open the console to view the error log, but also can debug js files. However, as we mentioned above, when specifying the production value by mode, the code is compressed, so debugging is a difficult task.

The Source Map is designed to solve this problem.

1) concept

The Source Map is an information file that stores location information, that is, the location Map after -> before – transformation. With its help, when an error occurs, the original code can be displayed directly instead of the converted compressed code, which can improve the efficiency of troubleshooting to a certain extent.

2) use

Under normal development environment, Webpack has Source Map function enabled by default, when the program runs wrong, you can directly prompt the information of the error location in the console

However, this kind of prompt is not friendly, because it records the position of the compressed code, which leads to the problem that the actual runtime error line does not match the number of lines in the source code, which can be a stumbling block in our path.

In that case, let’s solve the problem with the problem!

3) Problems encountered
① Problem 1:The number of lines that actually run with an errorThe number of lines of source codeDon’t match

To solve this problem, add the following configuration to webpack.config.js:

After the configuration, we can see that the number of error lines in the runtime matches the number of lines in the source code!

② Problem 2: easy to expose source code in the production environment

We’ve been able to locate errors in the source code, but exposing the source code in a production environment is not always a good idea, so we need to fix the problem as well.

The solution to this problem is also violent, specifying mode as production in the webpack.config.js file when packaging directly, so that no error lines are displayed, and no source content is displayed

mode: "production"
Copy the code

③ Problem 3: the production environment needs to display line number hidden source code

The above way is too violent, line count and source code will not show you. Is there a way to display the number of lines but not the source code? The answer is definitely there! We simply configure the devtool value to nosource-source-map

devtool: 'nosources-source-map'
Copy the code

After configuration, we will see the effect:

This method can display the error line number or hide the source code, which is a very suitable solution.

So let’s conclude

4) summary
  • The development environment

Setting devtool to eval-source-map helps pinpoint specific error lines

  • The production environment

Disable Source Map or set devtool to nosource-source-map to prevent Source leakage and improve security

END

Let’s this article from six points to summarize the basic use of Webpack, the back end of the students can icing on the cake, and after the end of the look can also be some common topics with front-end sister ~! Front-end students can review the old and learn new, may be a little rough, but to help pick mistakes, but also for their own consolidation foundation ~!

Don’t talk, don’t be lazy, and xiao CAI do a blowing bull X do architecture of the program ape ~ point a concern to do a companion, let xiao CAI no longer lonely. See you later!

Today you work harder, tomorrow you will be able to say less words!

I am xiao CAI, a man who grows stronger with you. 💋

Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!