Hello everyone, I am a side dish.
A man who hopes to be about architecture ! If you also want to be the person I want to be, otherwise click on your attention and be a companion, so that Xiaocai is no longer alone!
This article mainly introduces the use of
If necessary, you can refer to
If it helps, don’t forget to 1612c1f8f31292 ❥
WeChat public account has been opened, , students who have not followed please remember to pay attention!
Front End Cognition
Many people have a certain misunderstanding about front-end development. They feel that they will be H5 + C3 + JS is equivalent to front-end development, but in recent years the separation of front-end and back-end models has gradually become popular, indicating that the front-end is no longer as simple as before. .
From the perspective of my back-end, I feel that the front-end is a civil official, and the back-end is a military commander. I can’t say that I can be civil and military, but at least I can’t know . Take a step or two. When the current intern girl encounters Bug , if you, the front end of the pseudo-realm, can help~ Then in her eyes you are a who comes with colorful clouds~'
If you are Bootstrap plus Layui , then you can say that you are good at the front-end, and you will inevitably be shot on the beach~ Actual front-end development consists of the following modules:
- Modularization (js modularization, css modularization, resource modularization)
- componentization (reuse existing UI structure, style, behavior)
- standardization (division of directory structure, coding standardization, interface standardization, document standardization, Git branch management)
- automation (automated construction, automatic deployment, automated testing)
Just like the back end, all modules are available.
Speaking of engineering, mainstream solutions in back-end development include Maven project and Gradle project . Front-end engineering solutions also include webpack and vite . So let’s get to the topic of today, into Webpack
Webpack
1. Conceptual cognition
Essentially, webpack is a static module packaging tool JavaScript applications. When the webpack processes the application, it will build a
dependency graph from one or more entry points internally, and then combine each module required in your project into one or more bundles, all of which are static Resources, used to display your content.
The above content is excerpted from the official website, which is official. Let's briefly summarize below
- concept summary : webpack is a concrete solution for front-end project engineering
function summary :
- Provides friendly front-end modular development support
- Provides powerful functions such as code compression and confusion, handling browser compatibility with Js, and performance optimization
- advantages of : Improved front-end development efficiency and project maintainability
2. Basic use
Practice true knowledge 1612c1f8f31624! We use it directly to strengthen awareness.
First, we need to create a blank directory, and then execute npm init -y
in the blank directory to initialize the package management configuration file package.json
It can be simply understood that this package.json is equivalent to the pom.xml file in the maven project
In Maven project we are usually on the source code in src
directory under the WebPACK similar projects, so our next step is to create in the directory src
directory, then create two files index.html (Home page) and
index.js (script file)
We have traditionally imported Jquery files, generally there are two ways
- One is to download the jquery.mini.js file, and then introduce it into the project
<script src="../js/jquery.js"></script>
- One is to quote the CDN library that is available on the Internet, so you don’t need to download it
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Both methods have their own advantages and disadvantages, so I won't explain too much here!
Since our project is npm , then we can use npm to help us download the required packages
npm install jquery -s
After the addition is successful, we can see the package we just downloaded package.json file. Does this method remind you of the maven install
maven , this strange sense of familiarity~
After the jquery package is installed, we can view the newly installed package node_modules
Then reference in the project
Browser view JS running normally
The above method is also the traditional way of do . Next we will take a look at how the webpack is used.
1. Webpack installation
Run the following command in the terminal to install two packages related webpack
npm install webpack@5.42.1 webpack-cli@4.7.2 -D
extended
npm install xxx -S
, which isnpm install module_name --save
written into dependenciesnpm install xxx -D
, that is,npm install module_name --save-dev
write devDependenciesdevDependencies are some packages that we need to use when developing. They only need to be used in the development stage. These packages are not needed when they are packaged and launched.
dependencies , this one needs to be released to the production environment.
2. Webpack configuration
webpack.config.js in the root directory of the project, and initialize the following basic configuration:
module.exports = {
mode: "development"
}
Among them, mode is a variable value, there are two optional values
- development
1. Suitable for development environment
2. No code compression and performance optimization will be performed on the files generated by the package
3. The packaging speed is fast, suitable for use in the development stage, and can quickly respond to page changes
- production
1. Suitable for production environment
2. Code compression and performance optimization will be performed on the files generated by the package
3. The packaging speed is very slow, only suitable for use in the project release stage
1) The role of configuration files
webpack.config.js
is webpack profile, webpack before the actual start packing building will go read the configuration file , so based on the given configuration, the project package
Since webpack is a packaging tool developed based on node.js, it supports node.js-related syntax and modules for personalized configuration of webpack in its configuration file
Then let's make a loading point ① , first go back to the webpack just mentioned, and we will come back to introduce webpack later!
There is a familiar sentence in Java: Everything is an object , so we also have a sentence in front-end engineering: Everything is a module
We no longer need the traditional js import method:
<script src="../node_modules/jquery/dist/jquery.min.js"></script>
We may need jQuery place using Import way to import, jQuery is a page index.html need? No, but index.js script file needs, so we only need to import index.js
Then we also need to modify the package.json
file:
We added the dev script . The script under the script
node can be executed npm run
Then we run the npm run dev
command webpack to package and build the project
Snap it, soon! dist
directory is generated in the project directory, and there is a script file
We turn in index.html introduced the document main.js file, the first direct look at the results, we are right in the browser open
It can be found that js operating normally, so what is ?
The webpack 4.x and 5.x versions have the following default conventions:
- The default package entry file is
src/index.js
- The default output file path is
dist/main.js
stipulates that it is die, and people are alive , so we can modify the default packaging convention webpack.config.js
Now that you've agreed to, so we can know in main.js included in index.js content, we can see the direct main.js file, the results we expected
Let’s go back to the previous load point ① to continue just webpack.config.js configuration file description
We webpack.config.js can file entry
specified packaged entry node, then output
designated packaged exit node.
This is what we said above to break the default rules!
Above we have also finished the webpack , then let’s take a look at the plugin usage in webpack
Three, plug-in use
plug the name suggests is used to extend the WebPACK functions by installing and configuring third-party plug-ins can be extended WebPACK capacity, so that WebPACK more convenient to use. There are two most commonly used webpack
- webpack-dev-server
1. Similar to the nodemon tool used in the node.js stage
2. Whenever the source code is modified, webpack will automatically package and build the project
- html-webpack-plugin
1. Similar to a template engine
2. You can customize the content of the index.html page through this plugin
Let's first look at how to use the first plugin
1)webpack-dev-server
webpack-dev-server allows webpack monitor the changes in the project source code, so that
can be automatically packaged and built
① Installation
Use the following command to install the plugin in the project
npm install webpack-dev-server@3.11.2 -D
② Configuration
1, we need to modify package.json
in Script
"scripts": {
"dev": "webpack server"
}
2. Run the npm run dev
command
You can see a sentence: The project is running at localhost:8080/
. And after running, the dist
directory did not appear
Then we visit through this address but do not see the page we want, but need to click on the src
directory to access
Based on the above results, we may have the following questions:
- Why does
npm run dev
there will be an access address?
This is because webpack-dev-server will start a real-time packaged http server
- are the files generated by 1612c1f8f31fdd?
To answer this question, we need to know two things-the difference between webpack-dev-server
1. not configured with webpack-dev-server , the webpack package generated files will be stored on the actual physical disk (according to the output specified path)
2. When configured with webpack-dev-server , the packaged files will be stored in the memory and will no longer be stored according to output node. This has the advantage of improving the performance of real-time packaged output. , So memory is much faster than physical disk
- How to access the files generated in memory by
The files generated in the memory are placed in the root directory of the project by default, but they are virtually invisible. We can directly use /
represent the root directory of the project, followed by the name of the file to be accessed, then the files in the memory can be accessed .
To conclude with three questions, let’s html-webpack-plugin
2)html-webpack-plugin
We visited webpack server above and found that we could not directly access our index page. It is inevitable that there are some defects. If there are defects, there will be improvements. This can be talked about html-webpack-plugin this plug-in~!
① Installation
As usual, we need to install through the following command
npm install html-webpack-plugin@5.3.2 -D
② Configuration
③ Operation
We run npm run dev
and see the result
Through the plug-in, we can see that the page can be directly accessed through the path~
Some friends here may ask questions. If I don’t want to use 8080 can I access it localhost The answer is yes, we can do more configuration on the webpack-dev-server devServer node:
devServer: {
// 首次打包成功后,自动打开浏览器
open: true,
// 在 http 协议中,如果端口号是 80,则可以被省略
port: 8081,
// 指定运行的主机地址
host: '127.0.0.1'
},
Then we run the project and access the page 127.0.0.1:8081
So far we have introduced the use of two plug-ins, and then we will look at different things~!
Four, loader use
We have already said a word at the beginning, in front-end engineering, everything is a module. Therefore, we can import the jquery js file index.js script file by means of import css file be imported import We might as well give it a try:
When we wanted to import , the console gave us a sentence: You may need a proper loader to handle this file type , appropriate? loader? . Then enter the topic, what is loader !
In the actual development process, webpack can only package and process modules that end .js
Other modules that do not end with the suffix .js
webpack cannot be handled, that is, the situation above us will occur, but how to deal with it? Just as the prompt text says, we need to download an appropriate loader to handle this file type.
Loader loader There are many, but their role is only one, that is help webpack to package deal with specific file module
- css-loader : can package and process
.css
related files - less-loader : can package and process
.less
related files - babel-loader: can be packaged and processed webpack can not handle advanced JS syntax
Next, we will deal with the problem of the css
① Installation
Use the following command to install the laoder css
npm i style-loader@3.0.0 css-loader@5.2.6 -D
② Configuration
We need WebPACK .config.js configure the appropriate file Loader rules
module: {
rules: [
// 处理 .css 文件的 loader
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
]
}
③ Operation
Then we run the file and the browser sees the effect
The result has shown that css-loader has already played a role. Let's see how the rules are written:
{ test: /\.css$/, use: ['style-loader', 'css-loader'] }
test indicates the matching file type, use indicates the corresponding loader to be called
- order of loaders in the 1612c1f8f32452 use
- The calling sequence of multiple loader
from back to front
Other loader is used in the same way as above, all need to be installed first, and then configured webpack.config.js
1)less-loader
installation
npm i less-loader@10.0.1 less@4.1.1 -D
configuration
module: {
rules: [
// 处理 .css 文件的 loader
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
// 处理 .less 文件的 loader
{ test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] },
]
}
2)babel-loader
installation
npm i babel-loader@8.2.2 @babel/core@7.14.6 @babel/plugin-proposal-decorators@7.14.5 -D
configuration
module: {
rules: [
// 处理 .css 文件的 loader
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
// 处理 .less 文件的 loader
{ test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] },
// 处理JS高级语法的 loader
{ test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ }
]
}
Above we have seen several loader , so what is the processing flow? Let's explain with a picture:
Five, package release
After completing the above project development, we will come to packaging and publishing . Everything we have done before will definitely need to be released in the end. Then in order to make the project run with high performance in the production environment, we need to package the project. release.
① Configuration
Packaged and released the same needs to be configured, we need package.json
under document Script node configure:
Among them, --model
is a parameter item, which is used to specify webpack , which we have introduced above~ Then through the instruction npm run build
dist
directory in the root path of the project.
But if there is no specified rule configuration, the packaged files will be placed in the dist directory by default, but if we want to put the js file js directory, put the image in the we need to configure the corresponding configuration webpack.config.js
Previously, the generation directory of js file has been configured output node
Then we also need to configure the output directory of other files. Here is an example of image type files:
We are also webpack.config.js file, but this time it is configured in the rules node :
At this point, we have almost completed the packaging task, but if we change the js generation directory, what will happen at this time?
We found that redundant files were generated, and the old files were not deleted. Is it necessary to manually delete every time I package it? of course not! For each time the package will be released automatically clean out old files in the directory dist , you can install and configure Clean-WebPACK-plugin plug
installation
npm install clean-webpack-plugin@3.0.0 -D
configuration
run
Six, Source Map
This kind of Source Map is a bit interesting. After our backend is online, if there is a problem, we usually go to the server to check the error log. So if there is a problem in the front end, it is very convenient, we can directly open the console through F12 to view the error log, and we can also debug the js But we said above by the MODE designated production
compression values have code, then debug shall be a difficult task.
Source Map is used to solve this problem.
1) Concept
Source the Map is an information file, which stores location information, which is converted ->
location mapping before the conversion. With its help, when an error occurs, the original code can be directly displayed instead of the compressed code after conversion, which can improve the troubleshooting efficiency to a certain extent.
2) Use
Normally in the development environment, webpack is enabled by default Source Map function, when the program runs wrong, you can directly prompt the error location information on the console
But this kind of prompt is not friendly. It records the location of the compressed code. This causes the problem that the number of lines actually runs does not match the number of lines of the
source code. This will become our The stumbling block ~!
That being the case, then we will solve the problem with the problem!
3) Problems encountered
① Question 1: The number of lines in the actual running error does not match the number of lines in the source code of
So to solve this problem is also very simple, you need to add the following configuration webpack.config.js
After configuring and viewing the results, we can find that the number of lines of running error matches the
source code!
② Problem 2: The source code is easy to expose in the production environment
Although we have been able to locate the source code error above, it is not a good thing to expose the source code in the production environment, so we also have to solve the problem.
The way to solve this problem is also very violent. When directly packaging the webpack.config.js file, specify mode production
, so that the number of error lines will not be displayed, and the source content will not be displayed.
mode: "production"
③ Question 3: The production environment needs to display the number of lines to hide the source code
The above method is too violent, and the line number and source code are not shown to you. Is there a way to compare this, which can display the number of lines but not the source code? The answer is definitely there! We only need to configure the value of devtool nosources-source-map
devtool: 'nosources-source-map'
After configuration, we see the effect:
This method can not only display the number of error lines but also hide the source code, which is a very suitable solution.
So let's make a summary
4) Summary
- Development environment
Set the value of devtool eval-source-map
, which is conducive to accurately locate the specific error line
- production environment
Close Source Map or set the value of devtool nosource-source-map
, which will help prevent source code leakage and improve security
END
Let this from six o'clock to go summarizes WebPACK basic use, the back-end students can
icing on the cake, then bad after reading the front-end and sister can be somewhat common topic ~! Front-end students can
the new at 1612c1f8f3babf. This may be a bit rough, but to help pick the wrong, it is inevitable to consolidate the foundation for yourself~!
Don't talk empty talk, don't be lazy, and be a programmer with 1612c1f8f3bae4 bragging about X as an architecture~ Follow me to be a companion, so Xiao Cai is no longer alone. See you below!
If you work harder today, you will be able to say less begging words tomorrow!
I am Xiaocai, a man who becomes stronger with you.
💋
WeChat public account has been opened, , students who have not followed please remember to pay attention!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。