Webpack is a powerful build tool, and its rich and flexible configuration makes it difficult to use. Webpack-related questions can often be asked in interviews. If you just use scaffolding such as VUe-CLI without a thorough study of Webpack, you may not be able to answer them. I’m sure some interviewers won’t be able to ask questions without in-depth knowledge. Maybe two people will talk about how to configure the import and export, common loader, plugin.

As a youtiao front-end for many years, I have not faced up to the knowledge related to Webpack, let alone the interview questions related to Webpack. This time, I plan to study webpack-related content and record the learning content into webpack series, hoping that those who do not know webpack can master it.

Write a plug-in

Excerpt from Webpack Chinese documentation: Write a plug-in

Plug-ins provide third-party developers with the full capabilities of the WebPack engine. A functional module that focuses on a particular task in webPack compilation can be called a plug-in.

Create the plug-in

The WebPack plug-in consists of:

  • A Javascript naming function

  • Define an apply method on the prototype of the plug-in function

  • Specifies an event hook bound to WebPack itself

  • Handles specific data for webPack internal instances

  • The callback provided by WebPack is invoked when the functionality is complete

// a JavaScript naming function.
function MyExampleWebpackPlugin() {};// Define a 'apply' method on the prototype of the plug-in function.
MyExampleWebpackPlugin.prototype.apply = function(compiler) {
  // Specify an event hook to mount to webpack itself.
  compiler.plugin('webpacksEventHook'.function(compilation /* Handle specific data for webpack internal instances. * /, callback) {
    console.log("This is an example plugin!!!");

    // Call the webPack callback when the function is complete.
    callback();
  });
};
Copy the code

The Compiler and Compilation

The two most important resources in plug-in development are compiler and Compilation objects. The main function of the plug-in is to obtain the current configuration items and edit status according to the Compiler and compilation, and then participate in the compilation process through the hooks provided by the Compiler and compilation.

  • The Compiler object represents the complete Configuration of the WebPack environment. This object is created once when webPack is started, and all the actionable Settings are configured, including options, Loader, and plugin. When a plug-in is applied in a WebPack environment, the plug-in receives a reference to this Compiler object. You can use it to access the main webPack environment.

  • The compilation object represents a resource version build. When running the WebPack development environment middleware, each time a file change is detected, a new compilation is created, resulting in a new set of compilation resources. A compilation object represents the current module resources, the compile-generated resources, the changing files, and the state information of the dependencies being tracked. The Compilation object also provides a number of critical timing callbacks that plug-ins can choose to use when doing custom processing.

The core of plug-in development lies in the use of these two objects, its source in

  • Compiler Source

  • Compilation Source

Basic plug-in architecture

The plug-in is instantiated from a “Prototype object with apply methods.” The Apply method is called once by the Webpack Compiler when the plug-in is installed. The Apply method can receive a reference to the Webpack Compiler object, which can be accessed in the callback function. A simple plug-in structure looks like this:

function HelloWorldPlugin(options) {
  // Use options to set the plug-in instance...
}

HelloWorldPlugin.prototype.apply = function(compiler) {
  // Registers the function in the Done hook
  compiler.plugin('done'.function() {
    console.log('Hello World! ');
  });
};

module.exports = HelloWorldPlugin;
Copy the code

Then, to install the plugin, simply add an instance to your WebPack configuration’s Plugin array:

var HelloWorldPlugin = require('hello-world');

var webpackConfig = {
  / /... Here are the other configurations...
  plugins: [
    new HelloWorldPlugin({options: true}})];Copy the code

Accessing a compilation object

With Compiler objects, you can bind callbacks that provide compilation references and then retrieve each new compilation object. These compilation objects provide hook functions that hook into many steps of the build process.

function HelloCompilationPlugin(options) {}

HelloCompilationPlugin.prototype.apply = function(compiler) {

  // Set the callback to access the compilation object:
  compiler.plugin("compilation".function(compilation) {

    // Now set the callback to access the steps in compilation:
    compilation.plugin("optimize".function() {
      console.log("Assets are being optimized.");
    });
  });
};

module.exports = HelloCompilationPlugin;
Copy the code

Asynchronous compiled plug-in

Some asynchronous hooks require the additional use of the callBack function

function HelloAsyncPlugin(options) {}

HelloAsyncPlugin.prototype.apply = function(compiler) {
  compiler.plugin("emit".function(compilation, callback) {

    // do some asynchronous processing...
    setTimeout(function() {
      console.log("Done with async work...");
      callback();
    }, 1000);

  });
};

module.exports = HelloAsyncPlugin;
Copy the code

The sample

function FileListPlugin(options) {}

FileListPlugin.prototype.apply = function(compiler) {
  compiler.plugin('emit'.function(compilation, callback) {
    // In the makefile, create a header string:
    var filelist = 'In this build:\n\n';

    // Go through all compiled resource files,
    // For each file name, add a line of content.
    for (var filename in compilation.assets) {
      filelist += (The '-'+ filename +'\n');
    }

    // Insert this list as a new file resource into the WebPack build:
    compilation.assets['filelist.md'] = {
      source: function() {
        return filelist;
      },
      size: function() {
        returnfilelist.length; }}; callback(); }); };module.exports = FileListPlugin;
Copy the code

Welcome to the front-end birds to learn and communicate ~ 516913974