For a high-level introduction to writing plugins, start with How to write a plugin.

Many objects in Webpack extend the Tapable class, which exposes a plugin method. And with the plugin method, plugins can inject custom build steps. You will see compiler.plugin and compilation.plugin used a lot. Essentially, each one of these plugin calls binds a callback to fire at specific steps throughout the build process.

A plugin is installed once as Webpack starts up. Webpack installs a plugin by calling its apply method, and passes a reference to the Webpack compiler object. You may then call compiler.plugin to access asset compilations and their individual build steps. An example would look like this:

  1. // MyPlugin.js
  2. function MyPlugin(options) {
  3. // Configure your plugin with options...
  4. }
  5. MyPlugin.prototype.apply = function(compiler) {
  6. compiler.plugin("compile", function(params) {
  7. console.log("The compiler is starting to compile...");
  8. });
  9. compiler.plugin("compilation", function(compilation) {
  10. console.log("The compiler is starting a new compilation...");
  11. compilation.plugin("optimize", function() {
  12. console.log("The compilation is starting to optimize files...");
  13. });
  14. });
  15. compiler.plugin("emit", function(compilation, callback) {
  16. console.log("The compilation is going to emit files...");
  17. callback();
  18. });
  19. };
  20. module.exports = MyPlugin;

Then in webpack.config.js

  1. plugins: [
  2. new MyPlugin({options: 'nada'})
  3. ]

Note on interface types…

There are two types of plugin interfaces.

  • Timing based

    • sync (default): As seen above. Use return.
    • async: Last parameter is a callback. Signature: function(err, result)
    • parallel: The handlers are invoked parallel (async).
  • Return value

    • not bailing (default): No return value.
    • bailing: The handlers are invoked in order until one handler returns something.
    • parallel bailing: The handlers are invoked in parallel (async). The first returned value (by order) is significant.
    • waterfall: Each handler gets the result value of the last handler as an argument.

The Compiler instance

Plugins need to have the apply method on their prototype chain (or bound to) in order to have access to the compiler instance.

  1. //MyPlugin.js
  2. function MyPlugin() {};
  3. MyPlugin.prototype.apply = function (compiler) {
  4. //now you have access to all the compiler instance methods
  5. }
  6. module.exports = MyPlugin;

Something like this should also work

  1. //MyFunction.js
  2. function apply(options, compiler) {
  3. //now you have access to the compiler instance
  4. //and options
  5. }
  6. //this little trick makes it easier to pass and check options to the plugin
  7. module.exports = function(options) {
  8. if (options instanceof Array) {
  9. options = {
  10. include: options
  11. };
  12. }
  13. if (!Array.isArray(options.include)) {
  14. options.include = [ options.include ];
  15. }
  16. return {
  17. apply: apply.bind(this, options)
  18. };
  19. };

run(compiler: Compiler) async

The run method of the Compiler is used to start a compilation. This is not called in watch mode.

watch-run(watching: Watching) async

The watch method of the Compiler is used to start a watching compilation. This is not called in normal mode.

compilation(c: Compilation, params: Object)

A Compilation is created. A plugin can use this to obtain a reference to the Compilation object. The params object contains useful references.

normal-module-factory(nmf: NormalModuleFactory)

A NormalModuleFactory is created. A plugin can use this to obtain a reference to the NormalModuleFactory object.

  1. compiler.plugin("normal-module-factory", function(nmf) {
  2. nmf.plugin("after-resolve", function(data) {
  3. data.loaders.unshift(path.join(__dirname, "postloader.js"));
  4. });
  5. });

context-module-factory(cmf: ContextModuleFactory)

A ContextModuleFactory is created. A plugin can use this to obtain a reference to the ContextModuleFactory object.

compile(params)

The Compiler starts compiling. This is used in normal and watch mode. Plugins can use this point to modify the params object (i. e. to decorate the factories).

  1. compiler.plugin("compile", function(params) {
  2. //you are now in the "compile" phase
  3. });

make(c: Compilation) parallel

Plugins can use this point to add entries to the compilation or prefetch modules. They can do this by calling addEntry(context, entry, name, callback) or prefetch(context, dependency, callback) on the Compilation.

after-compile(c: Compilation) async

The compile process is finished and the modules are sealed. The next step is to emit the generated stuff. Here modules can use the results in some cool ways.

The handlers are not copied to child compilers.

emit(c: Compilation) async

The Compiler begins with emitting the generated assets. Here plugins have the last chance to add assets to the c.assets array.

after-emit(c: Compilation) async

The Compiler has emitted all assets.

done(stats: Stats)

All is done.

failed(err: Error)

The Compiler is in watch mode and a compilation has failed hard.

invalid()

The Compiler is in watch mode and a file change is detected. The compilation will be begin shortly (options.watchDelay).

after-plugins()

All plugins extracted from the options object are added to the compiler.

after-resolvers()

All plugins extracted from the options object are added to the resolvers.

The Compilation instance

The Compilation instance extends from the compiler. ie. compiler.compilation It is the literal compilation of all the objects in the require graph. This object has access to all the modules and their dependencies (most of which are circular references). In the compilation phase, modules are loaded, sealed, optimized, chunked, hashed and restored, etc. This would be the main lifecycle of any operations of the compilation.

  1. compiler.plugin("compilation", function(compilation) {
  2. //the main compilation instance
  3. //all subsequent methods are derived from compilation.plugin
  4. });

normal-module-loader

The normal module loader, is the function that actually loads all the modules in the module graph (one-by-one).

  1. compilation.plugin('normal-module-loader', function(loaderContext, module) {
  2. //this is where all the modules are loaded
  3. //one by one, no dependencies are created yet
  4. });

seal

The sealing of the compilation has started.

  1. compilation.plugin('seal', function() {
  2. //you are not accepting any more modules
  3. //no arguments
  4. });

optimize

Optimize the compilation.

  1. compilation.plugin('optimize', function() {
  2. //webpack is begining the optimization phase
  3. // no arguments
  4. });

optimize-tree(chunks, modules) async

Async optimization of the tree.

  1. compilation.plugin('optimize-tree', function(chunks, modules) {
  2. });

optimize-modules(modules: Module[])

Optimize the modules.

  1. compilation.plugin('optimize-modules', function(modules) {
  2. //handle to the modules array during tree optimization
  3. });

after-optimize-modules(modules: Module[])

Optimizing the modules has finished.

optimize-chunks(chunks: Chunk[])

Optimize the chunks.

  1. //optimize chunks may be run several times in a compilation
  2. compilation.plugin('optimize-chunks', function(chunks) {
  3. //unless you specified multiple entries in your config
  4. //there's only one chunk at this point
  5. chunks.forEach(function (chunk) {
  6. //chunks have circular references to their modules
  7. chunk.modules.forEach(function (module){
  8. //module.loaders, module.rawRequest, module.dependencies, etc.
  9. });
  10. });
  11. });

after-optimize-chunks(chunks: Chunk[])

Optimizing the chunks has finished.

revive-modules(modules: Module[], records)

Restore module info from records.

optimize-module-order(modules: Module[])

Sort the modules in order of importance. The first is the most important module. It will get the smallest id.

optimize-module-ids(modules: Module[])

Optimize the module ids.

after-optimize-module-ids(modules: Module[])

Optimizing the module ids has finished.

record-modules(modules: Module[], records)

Store module info to the records.

revive-chunks(chunks: Chunk[], records)

Restore chunk info from records.

optimize-chunk-order(chunks: Chunk[])

Sort the chunks in order of importance. The first is the most important chunk. It will get the smallest id.

optimize-chunk-ids(chunks: Chunk[])

Optimize the chunk ids.

after-optimize-chunk-ids(chunks: Chunk[])

Optimizing the chunk ids has finished.

record-chunks(chunks: Chunk[], records)

Store chunk info to the records.

before-hash

Before the compilation is hashed.

after-hash

After the compilation is hashed.

before-chunk-assets

Before creating the chunk assets.

additional-chunk-assets(chunks: Chunk[])

Create additional assets for the chunks.

record(compilation, records)

Store info about the compilation to the records

optimize-chunk-assets(chunks: Chunk[]) async

Optimize the assets for the chunks.

The assets are stored in this.assets, but not all of them are chunk assets. A Chunk has a property files which points to all files created by this chunk. The additional chunk assets are stored in this.additionalChunkAssets.

Here’s an example that simply adds a banner to each chunk.

  1. compilation.plugin("optimize-chunk-assets", function(chunks, callback) {
  2. chunks.forEach(function(chunk) {
  3. chunk.files.forEach(function(file) {
  4. compilation.assets[file] = new ConcatSource("\/**Sweet Banner**\/", "\n", compilation.assets[file]);
  5. });
  6. });
  7. callback();
  8. });

after-optimize-chunk-assets(chunks: Chunk[])

The chunk assets have been optimized. Here’s an example plugin from @boopathi that outputs exactly what went into each chunk.

  1. var PrintChunksPlugin = function() {};
  2. PrintChunksPlugin.prototype.apply = function(compiler) {
  3. compiler.plugin('compilation', function(compilation, params) {
  4. compilation.plugin('after-optimize-chunk-assets', function(chunks) {
  5. console.log(chunks.map(function(c) {
  6. return {
  7. id: c.id,
  8. name: c.name,
  9. includes: c.modules.map(function(m) {
  10. return m.request;
  11. })
  12. };
  13. }));
  14. });
  15. });
  16. };

optimize-assets(assets: Object{name: Source}) async

Optimize all assets.

The assets are stored in this.assets.

after-optimize-assets(assets: Object{name: Source})

The assets has been optimized.

build-module

Before a module build has started.

  1. compilation.plugin('build-module', function(){
  2. console.log('build module');
  3. });

succeed-module

A module has been built successfully.

  1. compilation.plugin('succeed-module', function(){
  2. console.log('succeed module');
  3. });

failed-module

The module build has failed.

  1. compilation.plugin('failed-module', function(){
  2. console.log('failed module');
  3. });

module-asset(module, filename)

An asset from a module was added to the compilation.

chunk-asset(chunk, filename)

An asset from a chunk was added to the compilation.

The MainTemplate instance

startup(source, module, hash)

  1. compilation.mainTemplate.plugin('startup', function(source, module, hash) {
  2. if (!module.chunks.length && source.indexOf('__ReactStyle__') === -1) {
  3. var originName = module.origins && module.origins.length ? module.origins[0].name : 'main';
  4. return ['if (typeof window !== "undefined") {',
  5. ' window.__ReactStyle__ = ' + JSON.stringify(classNames[originName]) + ';',
  6. '}'
  7. ].join('\n') + source;
  8. }
  9. return source;
  10. });

The Parser instance (compiler.parser)

The parser instance takes a String and callback and will return an expression when there’s a match.

  1. compiler.parser.plugin("var rewire", function (expr) {
  2. //if you original module has 'var rewire'
  3. //you now have a handle on the expresssion object
  4. return true;
  5. });

program(ast) bailing

General purpose plugin interface for the AST of a code fragment.

statement(statement: Statement) bailing

General purpose plugin interface for the statements of the code fragment.

call <identifier>(expr: Expression) bailing

abc(1) => call abc

a.b.c(1) => call a.b.c

expression <identifier>(expr: Expression) bailing

abc => expression abc

a.b.c => expression a.b.c

expression ?:(expr: Expression) bailing

(abc ? 1 : 2) => expression ?!

Return a boolean value to omit parsing of the wrong path.

typeof <identifier>(expr: Expression) bailing

typeof a.b.c => typeof a.b.c

statement if(statement: Statement) bailing

if(abc) {} => statement if

Return a boolean value to omit parsing of the wrong path.

label <labelname>(statement: Statement) bailing

xyz: abc => label xyz

var <name>(statement: Statement) bailing

var abc, def => var abc + var def

Return false to not add the variable to the known definitions.

evaluate <expression type>(expr: Expression) bailing

Evaluate an expression.

evaluate typeof <identifier>(expr: Expression) bailing

Evaluate the type of an identifier.

evaluate Identifier <identifier>(expr: Expression) bailing

Evaluate a identifier that is a free var.

evaluate defined Identifier <identifier>(expr: Expression) bailing

Evaluate a identifier that is a defined var.

evaluate CallExpression .<property>(expr: Expression) bailing

Evaluate a call to a member function of a successfully evaluated expression.

The NormalModuleFactory

before-resolve(data) async waterfall

Before the factory starts resolving. The data object has these properties:

  • context The absolute path of the directory for resolving.
  • request The request of the expression.

Plugins are allowed to modify the object or to pass a new similar object to the callback.

after-resolve(data) async waterfall

After the factory has resolved the request. The data object has this properties:

  • request The resolved request. It acts as an identifier for the NormalModule.
  • userRequest The request the user entered. It’s resolved, but does not contain pre or post loaders.
  • rawRequest The unresolved request.
  • loaders A array of resolved loaders. This is passed to the NormalModule and they will be executed.
  • resource The resource. It will be loaded by the NormalModule.
  • parser The parser that will be used by the NormalModule.

The ContextModuleFactory

before-resolve(data) async waterfall

after-resolve(data) async waterfall

alternatives(options: Array) async waterfall

Resolvers

  • compiler.resolvers.normal Resolver for a normal module
  • compiler.resolvers.context Resolver for a context module
  • compiler.resolvers.loader Resolver for a loader

Any plugin should use this.fileSystem as fileSystem, as it’s cached. It only has async named functions, but they may behave sync, if the user uses a sync file system implementation (i. e. in enhanced-require).

To join paths any plugin should use this.join. It normalizes the paths. There is a this.normalize too.

A bailing async forEach implementation is available on this.forEachBail(array, iterator, callback).

To pass the request to other resolving plugins, use the this.doResolve(types: String|String[], request: Request, callback) method. types are multiple possible request types that are tested in order of preference.

  1. interface Request {
  2. path: String // The current directory of the request
  3. request: String // The current request string
  4. query: String // The query string of the request, if any
  5. module: boolean // The request begins with a module
  6. directory: boolean // The request points to a directory
  7. file: boolean // The request points to a file
  8. resolved: boolean // The request is resolved/done
  9. // undefined means false for boolean fields
  10. }
  11. // Examples
  12. // from /home/user/project/file.js: require("../test?charset=ascii")
  13. {
  14. path: "/home/user/project",
  15. request: "../test",
  16. query: "?charset=ascii"
  17. }
  18. // from /home/user/project/file.js: require("test/test/")
  19. {
  20. path: "/home/user/project",
  21. request: "test/test/",
  22. module: true,
  23. directory: true
  24. }

resolve(context: String, request: String)

Before the resolving process starts.

resolve-step(types: String[], request: Request)

Before a single step in the resolving process starts.

module(request: Request) async waterfall

A module request is found and should be resolved.

directory(request: Request) async waterfall

A directory request is found and should be resolved.

file(request: Request) async waterfall

A file request is found and should be resolved.

The plugins may offer more extensions points

Here is a list what the default plugins in webpack offer. They are all (request: Request) async waterfall.

The process for normal modules and contexts is module -> module-module -> directory -> file.

The process for loaders is module -> module-loader-module -> module-module -> directory -> file.

module-module

A module should be looked up in a specified directory. path contains the directory.

module-loader-module (only for loaders)

Used before module templates are applied to the module name. The process continues with module-module.