Preface
Original intention: In this article, we will talk about Webpack, what it can do and why we should use it. Share the notes I have compiled with you. If you have any mistakes, please point out. If you don’t like it, don’t spray.
Suitable for the crowd: the front-end primary development, the big guys detour.
This article explains Webpack 4.x, pay attention to the version.
Why use Webpack
Before we are the traditional way to develop a system, html
, , css
, js
that's all. After the development is completed, it is directly deployed to the back-end personnel, of course, there is no problem. When our project requirements continue to increase, the more code becomes, the more difficult it is to maintain. There are hundreds or even thousands of lines of code in a file, and the code inside is even duplicated. You also need to worry about the script
label dependency order and the code. The problem of variable pollution is modularized at this time to prevent variable pollution and dependency order problems. Now the mainstream packaging tool is Webpack
strong community support and support Es Module
, CommonJs
and AMD
standardization.
What is Webpack
Webpack
Module is a packaged tool, you can Es Module
, CommonJs
grammar process into code that can run a browser, the dependent files associated packaged into a js
file.
What can Webpack do
Conducive to our convenient development, help us build a service locally, hot update of code changes and no page refresh, global injection of dependent files, code segmentation, code extraction, removal of unnecessary code, differentiation of environment variables, image optimization, etc., a strong community Plug-in extensions help us develop projects conveniently.
installation
The installation Webpack
environment is also very simple. Generally, local installation is recommended. Global installation may conflict with other projects. Try to install locally.
cnpm i webpack@4 webpack-cli --save
The webpack
grammar installed above is webpack-cli
the execution command of the command line operation
After the installation is complete, you can't directly webpack -v
report an error like this, because it will find your webpack
environment globally , but you are installing locally, and using npx webpack -v
this will perform a local search in your project.
Get started quickly
Initialize the package.json file
Execute this command under your project file, and fill in the corresponding (Enter all the way), foolish operation.
npm init
Project structure
|- /node_modules
|- /src
|- index.js
|- news.js
|- index.css
|- index.html
|- webpack.config.js
|- package.json
Entry
Entry packaging entry files, there are several forms of packaging entry, let's introduce them one by one.
Single entry
module.exports = {
entry: "./src/index.js"
}
Multi-entry
Multi-entry packaging, the js
file name is the key value of the object.
module.exports = {
entry: {
index: "./src/index.js",
news: "./src/news.js"
}
}
Array entry
Array packaging, entry
receiving an array object, only the last value of the parameter inside is the real packaging path, other parameters are to import the path file into the last parameter
module.exports = {
entry: ["./src/news.js", "./src/index.js"]
}
// 上面entry那种操作,等同于如下:
// index.js
require("news.js")
In the above example, except for the last parameter, all other array parameters are imported into the last parameter file
Output
output
If there is an entry file, there must be an export file,
module.exports = {
output: {
path: __dirname + "/dist",
filname: "app.js"
}
}
filename
There are several name options, let me introduce them
- [name] Use the name of the entry file
- [chunkhash] The hash value is generated, which is parsed by the current file depends on, and a chunk is generated at the end, and the hash value is generated
- [contenthash] When the content of the file changes, the hash value will change
- [id] Use chunk id to generate file name
- [hash] Use hash as the file name, each time the generated hash is different
module.exports = {
output: {
path: __dirname + "/dist",
filname: "[name][id][contenthash].js"
}
}
Loader
loader
What is it? We only talked about the js
relevant ones above. Webpack
By default, we only recognize js files. Then Webpack
how to package js
things js
other than packaging will report an error. What should I do? At this time loader
, it loader
is a converter. Let ’s follow Take the css
file as an example to explain
- test receives a regular expression, matches the file suffix name, and successfully enters the loader for execution
- use receives an array, when only one loader can be written as a string
css-loader
installation
npm i css-loader --save-dev
use
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ["css-loader"] or "css-loader"
}
]
}
}
After the configuration, loader
no error will be reported, but the code still does not take effect. It just parsed the css
file, but didn't style
mount it on the page, it needs to be combined style-loader
.
style-loader
installation
npm i style-loader --save-dev
use
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
"style-loader",
"css-loader"
]
}
]
}
}
In the above example, the loader must be executed sequentially, and the loader is executed from back to front. First, the css file is parsed, and then the parsed css file is mounted on the page style tag. At this time, the code will take effect.
Plugins
clean-webpack-plugin
At this time, if we modify the filename in the output and package it again, we can see that the old code in the previous dist package still exists. At this time, we want to generate a new dist directory every time we package, and then we need to use it To the plug-in.
Install the clean-webpack-plugin
plug-in, my local installation is version 3.0.0
npm i clean-wenpack-plugin --save-dev
use
const {
CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
plugins: [
new CleanWebpackPlugin()
]
}
html-webpack-plugin
If dist
there is no index.html
file in the directory after we have packaged it, then we can use the plug-in, and a html
file will be generated every time we package it , let’s install it below
The installation html-webpack-plugin
I use here is version 3.2.0. It should be noted that the node
higher your local version, the newer the plug-in installed, and the new version may be webpack4
a bit incompatible with or even cause code errors.
npm i html-webpack-plugin@3.2.0 --save-dev
use
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './index.html', // 以咱们本地的index.html文件为基础模板
filename: "index.html", // 输出到dist目录下的文件名称
}),
]
}
html-webpack-plugin
Receiving a plug-in object that has some property values, not one by one example where we can see the article "html-webpack-plugin uses the whole solution" .
Complete code
const {
CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: "./src/index.js",
output: {
path: __dirname + "/dist",
filename: "index.js"
},
module: {
rules: [
{
test: /\.css$/,
use: [
"style-loader",
"css-loader"
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './index.html',
filename: "index.html",
}),
]
}
to sum up
At this point, our webpack
introduction is finished, and a simple packaging is implemented. webpack
By default, only js
files are recognized . If you want to use css
and pictures, you can use loader
to convert. We can see the final package complete, dist
the directory or some of the original file html
, , css
, js
directly dist
contracted background deployed on the line.
For more frequently used ones to share in loader
the plugin
next issue, remember to follow me ❤❤❤.
thank
Thank you for reading this article. I hope it will be helpful to you. If you have any questions, please correct me.
I’m a frogman (✿◡‿◡), if you think it’s ok, please like it ❤.
Interested friends can join [Front-end entertainment circle exchange group] Welcome everyone to communicate and discuss
Writing is not easy, "Like" + "Watching" + "Repost" Thank you for your support❤
Good articles in the past
"Talk about using Decorator in Vue projects"
"Talk about what are CommonJs and Es Module and their difference"
"Map that takes you easily to understand the data structure"