Talk about the common Plugin in webpack? What problem has been solved?

1, What is it

Plug in (plug in) is a computer application that interacts with the main application to provide specific functions

It is a program written according to a certain standard application program interface, which can only run under the system specified by the program, because it needs to call the function library or data provided by the original system

The same is true for the plugin in webpack, which gives it various flexible functions, such as packaging optimization, resource management, environment variable injection, etc. they will run in different stages of webpack (hook / life cycle) and run through the whole compilation cycle of webpack

The purpose is to solve other things that loader # cannot achieve

collocation method

Here is the configuration method of the file. Generally, the plugins property in the exported object of the configuration file is passed into the new instance object. As follows:

const HtmlWebpackPlugin = require('html-webpack-plugin'); //Installation via # npm #
const webpack = require('webpack'); //Access built-in plug-ins
module.exports = {
  ...
  plugins: [
    new webpack.ProgressPlugin(),
    new HtmlWebpackPlugin({ template: './src/index.html' }),
  ],
};

2, Characteristics

Its essence is a javascript object with apply method

The apply  method will be called by the  webpack compiler, and the  compiler object can be accessed throughout the compilation life cycle

const pluginName = 'ConsoleLogOnBuildWebpackPlugin';

class ConsoleLogOnBuildWebpackPlugin {
  apply(compiler) {
    compiler.hooks.run.tap(pluginName, (compilation) => {
      console.log('webpack The build process begins!');
    });
  }
}

module.exports = ConsoleLogOnBuildWebpackPlugin;

The first parameter of compiler hook # tap method should be the name of the plug-in named in Hump style

The hooks for the whole compilation life cycle are as follows:

  • Entry option: initialization option

  • run

  • compile: the actual compilation starts before the compilation object is created

  • Compilation: the compilation object is generated

  • make starts from the entry, recursively analyzes dependencies, and prepares to build each module

  • After compile: the compile build process ends

  • emit: before writing the contents of assets in memory to the disk folder

  • After emit: after the contents of assets in memory are written to the disk folder

  • done: complete all the compilation process

  • failed: when compilation fails

3, Common Plugin

Common plugin s are as shown in the figure:

Here are some common plug-in usages:

HtmlWebpackPlugin

After the packaging is completed, automatically generate an html file, and lead the js module generated by the packaging into the html

npm install --save-dev html-webpack-plugin
// webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
 ...
  plugins: [
     new HtmlWebpackPlugin({
       title: "My App",
       filename: "app.html",
       template: "./src/html/index.html"
     }) 
  ]
};
<!--./src/html/index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><%=htmlWebpackPlugin.options.title%></title>
</head>
<body>
    <h1>html-webpack-plugin</h1>
</body>
</html>

In the html template, you can use <% = htmlwebpackplugin options. Get the configured value by XXX% >

More configurations can be found by self searching

clean-webpack-plugin

Delete (clean up) build directory

npm install --save-dev clean-webpack-plugin
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
module.exports = {
 ...
  plugins: [
    ...,
    new CleanWebpackPlugin(),
    ...
  ]
}

mini-css-extract-plugin

Extract CSS into a separate file

npm install --save-dev mini-css-extract-plugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
 ...,
  module: {
   rules: [
    {
     test: /\.s[ac]ss$/,
     use: [
      {
       loader: MiniCssExtractPlugin.loader
     },
          'css-loader',
          'sass-loader'
        ]
   }
   ]
 },
  plugins: [
    ...,
    new MiniCssExtractPlugin({
     filename: '[name].css'
    }),
    ...
  ]
}

DefinePlugin

It allows the creation of configured global objects at compile time. It is a webpack built-in plug-in and does not need to be installed

const { DefinePlugun } = require('webpack')

module.exports = {
 ...
    plugins:[
        new DefinePlugin({
            BASE_URL:'"./"'
        })
    ]
}

At this time, when compiling the template module, you can obtain the global object in the following form

<link rel="icon" href="<%= BASE_URL%>favicon.ico>"

copy-webpack-plugin

Copy files or directories to the execution area. For example, in the packaging process of vue, if we put some files in the public directory, this directory will be copied to the dist folder

npm install copy-webpack-plugin -D
new CopyWebpackPlugin({
    parrerns:[
        {
            from:"public",
            globOptions:{
                ignore:[
                    '**/index.html'
                ]
            }
        }
    ]
})

The copied rules are set in the patterns attribute:

  • From: sets which source to copy from

  • To: the location copied to, which can be omitted. It will be copied to the packaging directory by default

  • globOptions: set some additional options where you can write files that need to be ignored

Keywords: Webpack

Added by DJP1986 on Wed, 09 Feb 2022 11:44:51 +0200