Introduction of webpack plugin

hijiangtao

What's webpack plugin?

// webpack.config.js
var HelloWorldPlugin = require('hello-world');

module.exports = {
  // ... config settings here ...
  plugins: [new HelloWorldPlugin({ options: true })]
};

Composition of a plugin

  • A named JavaScript function or a JavaScript class.
  • Defines apply method in its prototype.
  • Specifies an event hook to tap into.
  • Manipulates webpack internal instance specific data.
  • Invokes webpack provided callback after functionality is complete.

Hello World

class HelloWorldPlugin {
  apply(compiler) {
    compiler.hooks.done.tap('Hello World Plugin', (
      stats /* stats is passed as argument when done hook is tapped.  */
    ) => {
      console.log('Hello World!');
    });
  }
}

module.exports = HelloWorldPlugin;


// webpack.config.js
var HelloWorldPlugin = require('hello-world');

module.exports = {
  // ... config settings here ...
  plugins: [new HelloWorldPlugin({ options: true })]
};

Compiler and hooks

If you don’t pass the webpack runner function a callback, it will return a webpack Compiler instance. This instance can be used to manually trigger the webpack runner or have it build and watch for changes, much like the CLI.

 

compiler.hooks.someHook.tap(/* ... */);

// 1. beforeRun - AsyncSeriesHook
// 2. entryOption - SyncBailHook
// 3. compilation - SyncHook
// etc...

Compilation and hooks

The Compilation module is used by the Compiler to create new compilations (or builds).

compilation.hooks.someHook.tap(/* ... */);

// 1. buildModule - SyncHook
// 2. succeedModule - SyncHook
// 3. afterOptimizeChunks - SyncHook
// etc...

Event hooks and type

compiler.hooks.done.tap(
	'HelloAsyncPlugin', 
    compilation => {
      console.log("webpack build done.");
    }
);

compiler.hooks.emit.tapAsync(
	'HelloAsyncPlugin', 
    (compilation, callback) => {
      setTimeout(function() {
        console.log('Done with async work...');
        callback();
      }, 1000);
    }
);

compiler.hooks.emit.tapPromise(
	'HelloAsyncPlugin', 
    compilation => {
      // return a Promise that resolves when we are done...
      return new Promise((resolve, reject) => {
        setTimeout(function() {
        console.log('Done with async work...');
        resolve();
      }, 1000);
      });
    }
);

Reference

Thanks