Welcome to wechat public account: Front Reading Room

Plug-ins are the backbone of WebPack. Webpack itself is built on top of the same plugin system you use in your WebPack configuration!

Plug-ins are designed to solve other things that loader cannot implement.

Tip

If the webpack-sources package is used in the plug-in, use require(‘webpack’).sources instead of require(‘webpack-sources’) to avoid persistent cached version conflicts.

Analyze the

The Webpack plug-in is a JavaScript object with the Apply method. The Apply method is called by the Webpack Compiler and the Compiler object is accessible throughout the compile life cycle.

ConsoleLogOnBuildWebpackPlugin.js

const pluginName = 'ConsoleLogOnBuildWebpackPlugin';

class ConsoleLogOnBuildWebpackPlugin {
  apply(compiler) {
    compiler.hooks.run.tap(pluginName, (compilation) = > {
      console.log('Webpack build process begins! '); }); }}module.exports = ConsoleLogOnBuildWebpackPlugin;
Copy the code

The first argument to compiler Hook’s tap method should be the camel-named plug-in name. It is recommended to use a constant for this so that it can be reused in all hooks.

usage

Since plug-ins can carry parameters/options, you must pass a new instance to the plugins property in the WebPack configuration.

Depending on your WebPack usage, there should be several ways to use the plug-in.

Configuration mode

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin'); // Install via NPM
const webpack = require('webpack'); // Access the built-in plug-in
const path = require('path');

module.exports = {
  entry: './path/to/my/entry/file.js'.output: {
    filename: 'my-first-webpack.bundle.js'.path: path.resolve(__dirname, 'dist'),},module: {
    rules: [{test: /\.(js|jsx)$/,
        use: 'babel-loader',}]},plugins: [
    new webpack.ProgressPlugin(),
    new HtmlWebpackPlugin({ template: './src/index.html'})]};Copy the code

ProgressPlugin is used to customize progress reports during compilation. HtmlWebpackPlugin will generate an HTML file and use script to introduce a JS file named my-first-webpack.bundle.js.

The Node API way

When using the Node API, plug-ins can also be passed in through the plugins property in the configuration.

some-node-script.js

const webpack = require('webpack'); // Access the WebPack runtime
const configuration = require('./webpack.config.js');

let compiler = webpack(configuration);

new webpack.ProgressPlugin().apply(compiler);

compiler.run(function (err, stats) {
  // ...
});
Copy the code

Tip

Did you know that the examples you saw above are very similar to the WebPack runtime itself? There are plenty of examples hidden in the WebPack source code that you can use in your own configurations and scripts.

Welcome to wechat public account: Front Reading Room