Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 38 ยท Plugins and Assets

Writing a Webpack Plugin

Learn how Webpack plugins work and write your own: the plugin class and apply method, compiler and compilation hooks, tapable, emitting a file, processAssets, options and testing ideas.

Every plugin you have used so far (HtmlWebpackPlugin, MiniCssExtractPlugin, DefinePlugin) follows the same simple contract. Webpack itself is built from plugins, so understanding the contract lets you read the source of any plugin, debug builds, and write your own for jobs no package covers: a build manifest, a license report, a custom banner, a size check.

The plugin contract

A plugin is a class (or any object) with an apply(compiler) method. Webpack calls it once at startup and passes the compiler, the object that represents the whole build. In apply you subscribe ("tap") to hooks, which are events fired at points of the build.

JavaScript
class HelloPlugin {
  apply(compiler) {
    compiler.hooks.done.tap('HelloPlugin', (stats) => {
      console.log('Build finished in', stats.endTime - stats.startTime, 'ms');
    });
  }
}

module.exports = { plugins: [new HelloPlugin()] };

tap('HelloPlugin', fn) registers a listener; the name appears in profiling and error messages. Hooks come from a small library named tapable. The main hook kinds:

Kind Behavior
SyncHook calls all listeners in order
AsyncSeriesHook listeners run one after another; use tapAsync or tapPromise
AsyncParallelHook async listeners run at once
SyncBailHook stops at the first listener that returns a value
SyncWaterfallHook each listener receives the previous one's result

Compiler versus compilation

  • The compiler lives for the whole process. It holds options and the top-level hooks: initialize, beforeRun, run, thisCompilation, emit, afterEmit, done.
  • A compilation is one build. In watch mode a new compilation is created for every rebuild. It holds the modules, chunks and assets of that build, and has its own hooks, such as processAssets.
flowchart LR
  A["compiler.hooks.run"] --> B["thisCompilation"]
  B --> C["compilation: build modules, make chunks"]
  C --> D["processAssets"]
  D --> E["emit"]
  E --> F["afterEmit"]
  F --> G["done"]

Plugins tap into this timeline. Most asset work happens at processAssets.

A stand-in for the hook system

The next demo implements a tiny hook mechanism and a fake build timeline, then runs a plugin against it. It is not Webpack and not the real tapable package, but the shape is the same.

Node.js Stand-in: hooks, taps and a plugin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A real plugin that emits a file

This version targets the real Webpack 5 API. Adding assets must happen at the right stage of processAssets, so other plugins (minifiers, hashing) treat the file correctly.

JavaScript
const { Compilation, sources } = require('webpack');

class BuildInfoPlugin {
  constructor(options = {}) {
    this.fileName = options.fileName ?? 'build-info.json';
  }

  apply(compiler) {
    const name = BuildInfoPlugin.name;

    compiler.hooks.thisCompilation.tap(name, (compilation) => {
      compilation.hooks.processAssets.tap(
        { name, stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL },
        (assets) => {
          const files = Object.keys(assets).map((file) => ({
            file,
            bytes: assets[file].size(),
          }));
          const info = { builtAt: new Date().toISOString(), files };
          compilation.emitAsset(this.fileName, new sources.RawSource(JSON.stringify(info, null, 2)));
        },
      );
    });
  }
}

module.exports = BuildInfoPlugin;

Points to note:

  • Use compilation.emitAsset(name, source) with a sources.RawSource, not direct writes to disk. Webpack writes (and in dev, serves from memory) the assets itself.
  • assets[file].size() gives the size of an existing asset.
  • Compilation.PROCESS_ASSETS_STAGE_* constants order the work: ADDITIONAL (add files), OPTIMIZE_SIZE (minifiers), SUMMARIZE, REPORT. Reading final sizes belongs late, for example at PROCESS_ASSETS_STAGE_REPORT.
  • Use tap for sync, tapAsync or tapPromise for async work. An async listener that never calls back hangs the build.

Failing and warning properly

Plugins should report problems through Webpack so they show in the normal output:

JavaScript
compilation.errors.push(new compilation.compiler.webpack.WebpackError('Bundle is too large'));
compilation.warnings.push(new compilation.compiler.webpack.WebpackError('Consider code splitting'));

A size-check plugin could do exactly that when an asset passes a limit. (Webpack's own performance.maxAssetSize option does this for you; building it yourself is a good exercise.)

Node.js Stand-in: a size budget plugin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Plugin design tips

  • Take options in the constructor, validate them early, and give clear defaults.
  • Do work in the right hook. Early hooks see configuration; processAssets sees outputs; done sees stats but cannot change files.
  • Be cache and watch friendly. Do not keep global state across compilations; store per-build data on compilation. Use compilation.fileDependencies.add(path) when you read an extra file so watch mode rebuilds when it changes.
  • Name your tap after the plugin so profiling output is readable.
  • Prefer existing plugins, and consider whether a loader is the better tool: loaders change one module's source, plugins act on the build as a whole.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Webpack call on a plugin object when the build starts?

    Webpack calls apply(compiler) once, and the plugin taps the hooks it needs.
  2. 2. What is the difference between compiler and compilation?

    Watch mode creates a new compilation per rebuild while the compiler persists.
  3. 3. Where should a plugin add a new output file?

    emitAsset lets Webpack write, serve and process the asset like any other.
  4. 4. Which tapable method must you use for a hook listener that returns a promise?

    Async hooks use tapAsync (callback) or tapPromise; plain tap is for sync hooks.

Summary

  • A plugin is an object with apply(compiler) that taps hooks from the tapable library.
  • The compiler is long-lived; a compilation is a single build and holds modules, chunks and assets.
  • Add files with compilation.emitAsset in processAssets, at the correct stage.
  • Report problems through compilation.errors and compilation.warnings.
  • Use loaders for per-file transforms and plugins for whole-build work; the demos here are stand-ins for the real hooks.

Next: Webpack Dev Server