For those who do not know webpack, you can go to webpack’s official website to learn the basic configuration. Here we will mainly learn common plug-in applications.

Loaders are used to package files, and plugins are used to solve other tasks such as uncomment and so on.

Grammar:

plugins:[plugin1,plugin2,plugin3]
Copy the code

The argument in the array must be an instance of the plug-in object, that is, new, as follows:

plugins: [
    new webpack.optimize.UglifyJsPlugin(),
    new HtmlWebpackPlugin({template: './src/index.html'})]Copy the code


1. HTML file generation plug-in: html-webpack-plugin

Generate background: Multiple entries, when your index.html introduces multiple jS’s, if the generated JS names have a hash, then the file name changes each time the package is packaged.

HtmlWebpackPlugin can be used to automatically regenerate an index.html or a template to help you import all the generated JS files into HTML and eventually generate them into the output directory.

Installation:

npm install --save-dev html-webpack-pluginCopy the code

Configuration:

// introduce const HtmlWebpackPlugin = require('html-webpack-plugin'); // Configure plugins: [new HtmlWebpackPlugin()]Copy the code

Of course, the above is the configuration of a single page. If you need to set the configuration of multiple pages, you need to instantiate multiple HtmlWebpackPlugin objects. In addition, we can also configure its parameters:

const htmlWebPackConfig = {    
    title: 'Hello Webpack'// Configure the template.' ', // template source HTML file filename:'index.html'// the generated template file name is favicon:' ', // Specify the icon for the pagehash: true, // whether to generatehashAdd at the end of the imported file address by defaulttrue    
    inject: ' '// The injection location of the imported template can be (true/false/body/head) minify: {// compress the generated HTML file. Default isfalse        
        collapseWhitespace: true, // whether to remove whitespacetrue, // Remove the attribute referencecaseSensitive: false, // whether case sensitive removeComments:true}, cache:true// generate a new file when the content changes. Defaulttrue    
    showErrors: true// Whether to write the error message on the page, defaulttrue   
    chunks: ['index'], // Import modules, which refer to multiple js Settings in the entry. In this case, execute JS, otherwise import all};Copy the code

Note: The above is for the convenience of expression, horizontal mark annotation, please use strict JSON format when using oh ~

Imagemin-webpack-plugin for image compression

Generate background: Images are too large, slow to load, and waste storage space.

Function: batch compression picture.

Installation:

npm install --save-dev imagemin-webpack-pluginCopy the code

Configuration:

Var ImageminPlugin = require()'imagemin-webpack-plugin').default; // Configure plugins: [new ImageminPlugin({disable: process.env.NODE_ENV ! = ='production'// Do not enable pngQuant during development: {// image quality:'95-100'}})]Copy the code

Clean -webpack-plugin

Generate background: You need to manually empty the target folder each time you pack.

What it does: Empty the output folder each time you pack.

Installation:

npm install --save-dev clean-webpack-pluginCopy the code

Configuration:

// Introduce const CleanWebpackPlugin = require('clean-webpack-plugin'); // Clean the dist folder plugins: [new CleanWebpackPlugin(['dist']]Copy the code

4. Provide global variable plug-ins

Generate background: Import global modules every time, very troublesome.

Function: It can be imported globally and no longer import on every page.

No installation required:

Built-in plugin: Webpack.providePluginCopy the code

Configuration:

New webpack.ProvidePlugin({jQuery:'jquery',
    React: 'react',
    ReactDOM: 'react-dom',
    Component: ['react'.'Component'// Export the React Component})Copy the code

5. Common Code extraction plug-ins

Background: CommonsChunkPlugin has been deprecated and replaced with optimisation. splitChunks, as in our project there are multiple references to common modules, or third-party libraries, which are repackaged.

Function: extract files that are repeatedly introduced, and generate one or more files separately, so as to avoid repackaging files in multiple entries.

Installation:

No installation, built-inCopy the code

Configuration:

SplitChunks :{cacheGroups: {vendor:{//node_modules dependencies: chunks:"all".test: /[\\/]node_modules[\\/]/,
                name:"vendor"MinSize: 0, priority:100, maxInitialRequests: 5, minSize: 0, priority:100, // enforce:true? }, common: {// 'SRC /js' is chunks:"all".test: / / \ \ / SRC / \ \ / js / \ \ / /, / / can also file / / \ \ / SRC / \ \ / js / \ \ /] * \. Js /, name:"common"MinChunks: 2, maxInitialRequests: 5, minSize: 0, priority:1}}}}Copy the code

To use with runtimeChunk:

Optimization. RuntimeChunk used to extract entry the chunk of the runtime function, form a single file, this part of the file does not vary over time, convenient for caching.

RuntimeChunk extracts the entry so that the entry file can be loaded quickly, and when something changes, only the changed place and the file change.

Configuration:

runtimeChunk: {
  name: 'manifest'
}Copy the code

Mini-css-extract-plugin (production mode)

Background: When packaging, CSS code will be packaged into JS, which is not good for file caching.

Function: Generate a single CSS file based on each entry (extract CSS from JS).

Installation:

npm install --save-dev mini-css-extract-pluginCopy the code

Configuration:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
plugins: [
  new MiniCssExtractPlugin(),
]Copy the code

Note:

  • Do not use in development mode as hot loading is not supported
  • If it’s single entry, you don’t need this

7. CSS removes unwanted styles

Background: The CSS written may be redundant.

Function: Remove redundant CSS code.

Installation:

npm install --save-dev purifycss-webpackCopy the code

Configuration:

const purifycssWebpack = require('purifycss-webpack');
const glob = require('glob'); // Make sure this is after ExtractTextPlugin! New purifycssWebpack ({paths: glob. Sync (path) resolve ('./src/*.html'))}),Copy the code

Note: HTML file generation > CSS Extraction > CSS tree shaker

File copy plugin: copy-webpack-plugin

Generate background: Some static resources (images, fonts, etc.) that need to be copied to the output folder at compile time.

Function: Used to copy files or folders.

Installation:

npm install --save-dev copy-webpack-pluginCopy the code

Configuration:

// introduce const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
  plugins: [
    new CopyPlugin([
      { from: 'source', to: 'dist' },
      { from: 'other/xx.js', to: 'dist'},])]};Copy the code


Above, is my more commonly used WebPack plug-in, detailed examples, can see my code oh ~

Big front, we refueling together, thank you for watching!!