Preface
Original intention: to share some useful things in work Plugin
, I hope it will be of some help to everyone, don't like it.
html-webpack-plugin
Purpose: Pack a page template into the dist directory, and by default it will automatically import js or css
installation
cnpm i html-webpack-plugin@3.2.0 -D
Configuration
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>首页</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './index.html', // 以咱们本地的index.html文件为基础模板
filename: "index.html", // 输出到dist目录下的文件名称
}),
]
}
HtmlWebpackPlugin
Receive an object, configure it yourself, see here for details
clean-webpack-plugin
Purpose: used to delete every package dist directory
installation
cnpm i clean-webpack-plugin -D
Configuration
webpack.config.js
const {
CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
plugins: [
new CleanWebpackPlugin()
]
}
extract-text-webpack-plugin
Purpose: Extract the css
style from the js
file and finally synthesize a css
file. The plug-in only supports the webpack4
previous version. If you are currently at webpack4
or above the version, an error will be reported.
installation
cnpm i extract-text-webpack-plugin -D
Configuration
webpack.config.js
const extractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: extractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
plugins: [
new extractTextPlugin({
filename: "[name].css",
allChunks: true
})
]
}
In the above configuration, the extractTextPlugin.extract
parameters inside fallback
are executed when the extraction is unsuccessful style-loader
. use
Which is used to extract css-loader
the conversion, plugins
which configuration filename
is finally finished merging .css
the file name, when allChunks
is false
the time, only when extracting initialization css
file for true
extracts when asynchronous css
file.
mini-css-extract-plugin
Purpose: The plug-in is exract-text-webpack-plugin
the same as the above , it extracts the css style, the only difference is the usage, webpack4
it is recommended to use it after the version of the plug-in
installation
cnpm i mini-css-extract-plugin -D
Configuration
webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader"
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "css/[name].css",
chunkFilename: "css/[name].css"
})
]
}
In the above configuration, you can see the usage and the exract-text-webpack-plugin
difference, let's take a look at the difference.
loader
No configurationfallback
- In
plugin
settingfilename
the synchronization load the resource name, also specify asynchronous loadingcss
of resourceschunkFilename
- The plug-in supports configuration
publicPath
to setcss
the path of asynchronous loading exract-text-webpack-plugin
Only one css file will be extracted, and itmini-css-extract-plugin
will be extracted based on the asynchronous file.
webpack.optimize.CommonsChunkPlugin
Purpose: Used to extract the common code in the page, so as to optimize the loading speed, this CommonsChunkPlugin
only supports the Webpack4
previous.
installation
该插件是Webpack内置的,不需要安装。
Configuration
main.js
import Vue from "vue"
webpack.config.js
module.exports = {
entry: {
main: "./main.js",
vendor: ["Vue"]
},
plugins: [
new Webpack.optimize.CommonsChunkPlugin({
name: "vendor",
filename: "[name].js"
}),
new Webpack.optimize.CommonsChunkPlugin({
name: "common",
chunks: ["vendor"],
filename: "[name].js"
})
]
}
In the above configuration, we extract and optimize main.js
the dependent files in Vue.js
it to avoid loading this js
file every time you package or visit other pages . We first Vue
extract the basic environment, because the basic environment will hardly change , So that extraction optimization is necessary. Then Webpack
extract the runtime code, so that vendor
it won’t change if you package it again, you can use the browser cache
optimization.SplitChunks
Purpose: This function is the webpack.optimize.CommonsChunkPlugin
same as above , but it optimization.SplitChunks
is webpack4
recommended to use later
installation
内置的,不需要安装。
Configuration
main.js
import Vue from "vue"
console.log(Vue)
import("./news")
news.js
import Vue from "vue"
console.log(Vue)
webpack.config.js
module.exports = {
mode: "development",
entry: {
main: "./main.js"
},
output: {
filename: "[name].js",
path: __dirname + "/dist"
},
optimization: {
splitChunks: {
chunks: "all"
}
},
}
In the above configuration, splitChunks
the chunks
as all
is all chunk
take effect by default only async
valid asynchronous.
splitChunks
There is also automatic extraction by default, and the default requirements are as follows:
- The extracted modules are from the
node_module
catalog - Module is larger than 30kb
- When loading on demand, the maximum requested resource is less than or equal to 5
- The maximum number of parallel requests at the first load is less than or equal to 3
DefinePlugin
Purpose: Used to inject global variables, generally used in environment variables.
installation
无需安装,webpack内置
Configuration
webpack.config.js
const Webpack = require("webpack")
module.exports = {
plugins: [
new Webpack.DefinePlugin({
STR: JSON.stringify("蛙人"),
"process.env": JSON.stringify("dev"),
name: "蛙人"
})
]
}
In the above configuration, DefinePlugin
an object is received, and the key
value inside corresponds to a value
value. This value
value is a code snippet. You can see the above one name
, and an error will be reported 蛙人 is not defined
. Please note here that the value
value must be a variable or a code snippet .
ProvidePlugin
Purpose: Used to define global variables, such as importing 100 pages, importing vue
each page will only increase the workload, just webpackProvide
mount a variable directly , no need to import one by one.
installation
无需安装,webpack内置
Configuration
webpack.config.js
const Webpack = require("webpack")
module.exports = {
plugins: [
new Webpack.ProvidePlugin({
"Vue": ["vue", "default"]
})
]
}
In the above configuration, ProvidePlugin
an object key
is received, the value is the variable used, the value
first parameter of the value is the Vue
module, and the second parameter is the default Es Module.default
attribute. import
The default is the introduction of a coming Es Module
object, which has default
this property is the entity object
hot-module-replacement-plugin
Purpose: open hot module update
installation
无需安装,webpack内置
Configuration
webpack.config.js
const Webpack = require("webpack")
module.exports = {
plugins: [
new Webpack.HotModuleReplacementPlugin()
]
}
IgnorePlugin
Purpose: Used to filter packaged files and reduce the size of packaged files.
installation
无需安装,webpack内置
Configuration
webpack.config.js
const Webpack = require("webpack")
module.exports = {
plugins: [
new Webpack.IgnorePlugin(/.\/lib/, /element-ui/)
]
}
uglifyjs-webpack-plugin
Purpose: Used to compress js
files, aiming at webpack4
versions and above.
installation
cnpm install uglifyjs-webpack-plugin -D
Configuration
webpack.config.js
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
optimization: {
minimizer: [
new UglifyJsPlugin({
test: /\.js(\?.*)?$/i,
exclude: /node_modules/
})
]
}
}
copy-webpack-plugin
Purpose: used to copy files to a directory
installation
cnpm i copy-webpack-plugin@6.4.1 -D
Configuration
webpack.config.js
const CopyWebpackPlugin=require('copy-webpack-plugin');
module.exports = {
plugins: [
new CopyWebpackPlugin({
patterns: [
{
from: "./main.js",
to: __dirname + "/dist/js",
toType: "dir"
}
]
})
]
}
In the above configuration, will be main.js
copied to the dist
directory js
, the toType
default file
may be set to dir
, because my dist
no directory js
catalog.
optimize-css-assets-webpack-plugin
Purpose: Used to compress css style
installation
cnpm i optimize-css-assets-webpack-plugin -D
Configuration
webpack.config.js
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin")
module.exports = {
plugins: [
new OptimizeCssAssetsWebpackPlugin(),
]
}
imagemin-webpack-plugin
Purpose: used to compress pictures
installation
cnpm i imagemin-webpack-plugin -D
Configuration
webpack.config.js
const ImageminPlugin = require('imagemin-webpack-plugin').default
module.exports = {
plugins: [
new ImageminPlugin({
test: /\.(jpe?g|png|gif|svg)$/i
})
]
}
friendly-errors-webpack-plugin
Purpose: to beautify the console, to prompt errors well. We don’t want our terminal to start up messy, like this
installation
cnpm i friendly-errors-webpack-plugin -D
Configuration
webpack.config.js
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const devServer = {
publicPath: "/",
port: 9527,
host: "localhost",
open: true,
hotOnly: true,
stats: 'errors-only'
}
module.exports = {
plugins: [
new FriendlyErrorsWebpackPlugin({
compilationSuccessInfo: {
notes: ['蛙人你好,系统正运行在http://localhost:' + devServer.port]
},
clearConsole: true,
})
],
devServer
}
After running the above code. See the following results
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 ❤.
Writing is not easy, "Like" + "Watching" + "Repost" Thank you for your support❤
Good articles in the past
"Teach you how to write a Vue component to publish to npm and it can be used outside the chain"
"Share 12 commonly used Loaders in Webpack"
"Talk about what are CommonJs and Es Module and their difference"
"Map that takes you easily to understand the data structure"