Webpack custom plug-in writing

When writing a custom plug-in, you need to know that the webpack plug-in consists of the following:

  • A JavaScript named function or JavaScript class.
  • Define an apply method on the prototype of the plug-in function.
  • Specify an event hook bound to the webpack itself.
  • Process specific data for webpack internal instances.
  • Call the callback provided by webpack after the function is completed.

Basic plug-in architecture

The plug-in is instantiated by the "prototype object with the {apply} method". This # apply # method will be called once by the webpack compiler when installing the plug-in. The apply} method can receive a reference to a webpack compiler object so that the compiler object can be accessed in the callback function. The structure of a plug-in is as follows:

class HelloWorldPlugin {
  apply(compiler) {
    compiler.hooks.done.tap(
      'Hello World Plugin',
      (
        stats /* After binding the done hook, stats will be passed in as a parameter. */
      ) => {
        console.log('Hello World!');
      }
    );
  }
}

module.exports = HelloWorldPlugin;

Webpack will broadcast many events in the running life cycle. Plugin can listen to these events and hook in the custom functions you want to add at a specific stage. The Tapable event flow mechanism of webpack ensures the order of plug-ins and makes the whole system extensible.

  • compiler exposes hooks associated with the entire lifecycle of Webpack
  • compilation exposes finer grained event hooks related to modules and dependencies
  • The plug-in needs to bind the apply method on its prototype to access the compiler instance
  • The compiler and compilation objects passed to each plug-in are the same reference. If their properties are modified in a plug-in, subsequent plug-ins will be affected
  • Find the appropriate event point to complete the desired function
    • When the emit event occurs, you can read and modify the final output resources, code blocks, modules and their dependencies (the emit event is the last time to modify the Webpack output resources)
    • Watch run is triggered when the dependent file changes
  • Asynchronous events need to call the callback function when the plug-in finishes processing the task to inform Webpack to enter the next process, otherwise it will get stuck

For a recent project, you need to judge whether the current version number is the latest after each packaging and distribution, so as to prompt the user that the version has been updated. The implementation idea is to package the package Take out the version number in json and automatically generate a json static file when packaging and put it in the packaged directory. In this way, you can dynamically take the version number in this file and compare it with the version number in the project to determine whether the current code is the latest.

Create custom plug-ins

Here, take vue project as an example, create a js file extra webpack plugin in the project directory js to store the code of the plug-in

/** Customized plug-in: generate version number json file */
const { version } = require("./package.json");
const fs = require("fs");
class VersionPlugin {
  apply(compiler) {
    // emit is an asynchronous hook. You can touch it with tapAsync, and you can also use tappromise / tap (synchronization)
    compiler.hooks.emit.tap("Version Plugin", (compilation) => {
      const outputPath = compiler.path || compilation.options.output.path;
      const versionFile = outputPath + "/version.json";
      const content = `{"version": "${version}"}`;

      /** Returns true if the path exists, otherwise false. */
      if (!fs.existsSync(outputPath)) {
        // Create directories synchronously. Returns the first directory path that was undefined or created (if recursive is true). This is FS Synchronized version of mkdir().
        fs.mkdirSync(outputPath, { recursive: true }); 
      }

      // http://nodejs.cn/api-v14/fs.html#fs_fs_writefilesync_file_data_options
      fs.writeFileSync(versionFile, content, {
        encoding: "utf8",
        flag: "w",
      });
    });
  }
}

module.exports = { VersionPlugin };

How to use custom plug-ins

To install this plug-in, just install it in your Vue config. Add an instance to the plugin array of JS configuration, so that the custom plug-in will be executed when packaging and running. After packaging, a version. Exe will be generated in the dist directory JSON file.

const { FileListPlugin } = require('./extra-webpack-plugin');

const vueConfig = {
    publicPath: process.env.VUE_PUBLIC_PATH || '/',
    configureWebpack: {
        plugins: [
            // Custom plug-ins
            new VersionPlugin()
        ]
    }
}

module.exports = vueConfig

The above is a simple attempt to customize the webpack plug-in. For specific usage and other API s, please refer to the official documents.

Tags: Javascript Front-end Webpack

Posted by Smasher on Fri, 20 May 2022 00:03:21 +0300