To make Webpack work for us, we not only need to be comfortable with loader, but also need to be comfortable with plugins.
Pre: This article undertakes full parsing of loader
If we compare Webpack to a soybean milk machine, we need a cup of soybean milk to drink, we need:
- Prepare raw materials, such as the processing of our entry point;
- Choosing soya-milk varieties is like choosing a loader;
- The stirring motor works like our plugins;
- Finish pouring out taste, like our output file processing;
- Power supply online, like usdevServerThe service is enabled.
The purpose of this graphic metaphor is to help us understand how WebPack works. To use it well, we must understand the principle and usage of each module.
Here are some highlights of how plugins can be used:
Plugins
Loaders only perform transformations on a per-file basis, while plugins are more commonly used (but not limited to) to perform operations and custom functions during the “compilation” and “chunk” life cycles of packaged modules. Webpack’s plug-in system is extremely powerful and customizable.
-
How to use it: To use a plugin, you simply require() it and add it to the plugins array. Most plug-ins can be customized with options. You can also use the same plug-in multiple times in a configuration file for different purposes, creating an instance of it by using new. The configuration in webpack.config.js is as follows:
const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); const path = require('path'); Const config = {// entry configuration:'./path/to/my/entry/file.js'// output: {path: path.resolve(__dirname,'dist'), filename: 'my-first-webpack.bundle.js'}, // module load conversion module: {rules: [{test: /\.txt$/, use: 'raw-loader'}]}, // Plugins call to complete the function custom plugins: [/ / compression js plug-in new webpack. Optimize. UglifyJsPlugin (), / / to the index. The HTML file for the template to generate HTML 5 new file new HtmlWebpackPlugin ({template:'./src/index.html'}})]; module.exports = config;Copy the code
Examples of common WebPack plug-ins
Webpack has a rich plugin interface. Most of the functionality of WebPack itself uses this plug-in interface. This plug-in interface makes WebPack extremely flexible. For more plug-ins, please visit the official website.
-
CommonsChunkPlugin The CommonsChunkPlugin is an opt-in feature that creates a separate file (known as a chunk), consisting of common modules shared between multiple entry points. By separating common modules from bundles, the resulting chunked file can be loaded once initially, and stored in cache for later use. This results in pagespeed optimizations as the browser can quickly serve the shared code from cache, rather than being forced to load a larger bundle whenever a new page is visited. This plugin allows you to separate and merge multiple modules into a common module file that the browser loads once, making the page load faster. Note: This plug-in is built into WebPack and does not need to be installed
Method of use: new webpack.optimize.Com monsChunkPlugin (options)
Configuration:
{name: string, // or names: string[], // This is the name of common Chunk. An existing chunk can be selected by passing in an existing chunk name. // If an array of strings is passed in, this corresponds to the plugin calling filename: string multiple times for each chunk name, // the common Chunk filename template. Can contain the same placeholder as' output.filename '. minChunks: number|Infinity|function(module, count) -> Boolean, // Minimum number of chunks required before Commons chunks are passed in. // The number of chunks must be greater than or equal to 2, or less than or equal to the number of chunks: string[], // Select the source of the chunks by the chunk name. Chunk must be a submodule of the public chunk. // If omitted, all, all entry chunks will be selected. Children: Boolean, // if set totrueDeepChildren: Boolean, // If ', all submodules of the public chunk will be selectedtrue` all descendants of the Commons chunk are selected async: Boolean | string, / / if set to `true', an asynchronous public chunk will be created as a submodule of 'options.name' and a sibling of 'options.chunks'. MinSize: number, // The minimum size of all common modules before the public chunk is created. }Copy the code
For example:
/ / to extract common file new webpack.optimize.Com monsChunkPlugin ({name:'reset',
filename: 'vendor/common.js', //(modules must be shared by 3 chunks) minChunks: 3}),Copy the code
- ExtractTextWebpackPlugin Extract text from a bundle, or bundles, into a separate file. This plugin is used to separate out a single file
Installation:
npm install --save-dev extract-text-webpack-pluginCopy the code
Usage:
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("styles.css")]}Copy the code
It moves all the *.css references in entry chunks to separate CSS files. Therefore, your styles will no longer be embedded in the JS bundle, but in a separate CSS file (i.e., styles.css).
- HotModuleReplacementPlugin
Module Hot Replacement plug-in enables Hot Module Replacement, also known as HMR.
Note: Never enable HMR in production
Usage:
Enabling HMR is simple and in most cases does not require setting options.new webpack.HotModuleReplacementPlugin({ // Options... })Copy the code
- HtmlWebpackPlugin it simplifies the creation of HTML files to serve your Webpack. This is especially useful for Webpack bundles that include hashes in their file names that change each time they mutate.
The installation
npm install --save-dev html-webpack-pluginCopy the code
Usage: SPA single page:
const HtmlWebpackPlugin = require('html-webpack-plugin');
var webpackConfig = {
entry: 'index.js',
output: {
path: 'dist',
filename: 'index_bundle.js'
},
plugins: [new HtmlWebpackPlugin()]
};
module.exports = webpackConfig;Copy the code
This will produce a file dist/index.html containing the following:
<! DOCTYPE html> <html> <head> <meta charset="UTF-8">
<title>webpack App</title>
</head>
<body>
<script src="index_bundle.js"></script>
</body>
</html>Copy the code
Multi-page:
{
entry: 'index.js',
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin(), // Generates default index.html
new HtmlWebpackPlugin({ // Also generate a test.html
filename: 'test.html',
template: 'src/assets/test.html'}})]Copy the code
- ProvidePlugin
Automatically load modules without having to import or require everywhere.
When our application uses a lot of jQuery or Zepto, we can use this plug-in for identification once and everywhere.
Note: WebPack is built-in and does not need to be installed
To automatically load jquery, we can point both variables to the corresponding Node module:new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' })Copy the code
Use: Lodash Map
new webpack.ProvidePlugin({ _map: ['lodash'.'map']})Copy the code
- UglifyjsWebpackPlugin to minify your JavaScript. UglifyjsWebpackPlugin to minify your JavaScript. UglifyjsWebpackPlugin to minify your JavaScript.
Installation:
npm i -D uglifyjs-webpack-pluginCopy the code
Usage:
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
plugins: [
new UglifyJSPlugin()
]
}Copy the code
Configuration items:
{
parse: {
// parse options
},
compress: {
// compress options
},
mangle: {
// mangle options
properties: {
// mangle property options
}
},
output: {
// output options
},
sourceMap: {
// source map options
},
ecma: 5, // specify one of: 5, 6, 7 or 8
nameCache: null, // or specify a name cache object
toplevel: false,
ie8: false,
warnings: false,}Copy the code
Please refer to Uglifyjs official website for more parameters