Printable

Introduction

A variety of interfaces are available to customize the compilation process. Some features overlap between interfaces, e.g. a configuration option may be available via a CLI flag, while others exist only through a single interface. The following high-level information should get you started.

CLI

The Command Line Interface (CLI) to configure and interact with your build. It is especially useful in the case of early prototyping and profiling. For the most part, the CLI is simply used to kick off the process using a configuration file and a few flags (e.g. --env).

Learn more about the CLI!

Module

When processing modules with webpack, it is important to understand the different module syntaxes -- specifically the methods and variables -- that are supported.

Learn more about modules!

Node

While most users can get away with just using the CLI along with a configuration file, more fine-grained control of the compilation can be achieved via the Node interface. This includes passing multiple configurations, programmatically running or watching, and collecting stats.

Learn more about the Node API!

Loaders

Loaders are transformations that are applied to the source code of a module. They are written as functions that accept source code as a parameter and return a new version of that code with transformations applied.

Learn more about loaders!

Plugins

The plugin interface allows users to tap directly into the compilation process. Plugins can register handlers on lifecycle hooks that run at different points throughout a compilation. When each hook is executed, the plugin will have full access to the current state of the compilation.

Learn more about plugins!

Command Line Interface

For proper usage and easy distribution of this configuration, webpack can be configured with webpack.config.js. Any parameters sent to the CLI will map to a corresponding parameter in the config file.

Read the installation guide if you don't already have webpack and CLI installed.

Usage with config file

webpack [--config webpack.config.js]

See configuration for the options in the configuration file.

Usage without config file

webpack <entry> [<entry>] -o <output>

<entry>

A filename or a set of named filenames which act as the entry point to build your project. You can pass multiple entries (every entry is loaded on startup). If you pass a pair in the form <name>=<request>, you can create an additional entry point. It will be mapped to the configuration option entry.

<output>

A path and filename for the bundled file to be saved in. It will be mapped to the configuration options output.path and output.filename.

Example

If your project structure is as follows -

.
├── dist
├── index.html
└── src
    ├── index.js
    ├── index2.js
    └── others.js
webpack src/index.js -o dist/bundle.js

This will bundle your source code with entry as index.js, and the output bundle file will have a path of dist, and the filename will be bundle.js

	| Asset     | Size    | Chunks      | Chunk Names |
	|-----------|---------|-------------|-------------|
	| bundle.js | 1.54 kB | 0 [emitted] | index       |
	[0] ./src/index.js 51 bytes {0} [built]
	[1] ./src/others.js 29 bytes {0} [built]
webpack index=./src/index.js entry2=./src/index2.js -o dist/bundle.js

This will form the bundle with both the files as separate entry points.

	| Asset     | Size    | Chunks        | Chunk Names   |
	|-----------|---------|---------------|---------------|
	| bundle.js | 1.55 kB | 0,1 [emitted] | index, entry2 |
	[0] ./src/index.js 51 bytes {0} [built]
	[0] ./src/index2.js 54 bytes {1} [built]
	[1] ./src/others.js 29 bytes {0} {1} [built]

Common Options

Note that Command Line Interface has a higher precedence for the arguments you use it with than your configuration file. For instance, if you pass --mode="production" to webpack CLI and your configuration file uses development, production will be used.

List all of the options available on the cli

webpack --help
webpack -h

Build source using a config file

Specifies a different configuration file to pick up. Use this if you want to specify something different from webpack.config.js, which is the default.

webpack --config example.config.js

Print result of webpack as a JSON

webpack --json
webpack --json > stats.json

In every other case, webpack prints out a set of stats showing bundle, chunk and timing details. Using this option, the output can be a JSON object. This response is accepted by webpack's analyse tool, or chrisbateman's webpack-visualizer, or th0r's webpack-bundle-analyzer. The analyse tool will take in the JSON and provide all the details of the build in graphical form.

Environment Options

When the webpack configuration exports a function, an "environment" may be passed to it.

webpack --env.production    # sets env.production == true
webpack --env.platform=web  # sets env.platform == "web"

The --env argument accepts various syntaxes:

Invocation Resulting environment

Invocation

Resulting environment

webpack --env prod

"prod"

"prod"

Invocation

Resulting environment

webpack --env.prod

{ prod: true }

{ prod: true }

Invocation

Resulting environment

webpack --env.prod=1

{ prod: 1 }

{ prod: 1 }

Invocation

Resulting environment

webpack --env.prod=foo

{ prod: "foo" }

{ prod: "foo" }

Invocation

Resulting environment

webpack --env.prod --env.min

{ prod: true, min: true }

{ prod: true, min: true }

Invocation

Resulting environment

webpack --env.prod --env min

[{ prod: true }, "min"]

[{ prod: true }, "min"]

Invocation

Resulting environment

webpack --env.prod=foo --env.prod=bar

{prod: [ "foo", "bar" ]}

{prod: [ "foo", "bar" ]}

See the environment variables guide for more information on its usage.

Config Options

Parameter Explanation Input type Default

Parameter

Explanation

Input type

Default

--config

Path to the config file

Path to the config file string webpack.config.js or webpackfile.js

Parameter

Explanation

Input type

Default

--config-register, -r

Preload one or more modules before loading the webpack configuration

Preload one or more modules before loading the webpack configuration array

Parameter

Explanation

Input type

Default

--config-name

Name of the config to use

Name of the config to use string

Parameter

Explanation

Input type

Default

--env

Environment passed to the config, when it is a function

Environment passed to the config, when it is a function

Parameter

Explanation

Input type

Default

--mode

Mode to use, either "development" or "production"

Mode to use, either "development" or "production" string

Output Options

This set of options allows you to manipulate certain output parameters of your build.

Parameter Explanation Input type Default

Parameter

Explanation

Input type

Default

--output-chunk-filename

The output filename for additional chunks

The output filename for additional chunks string filename with [ id ] instead of [ name ] or [ id ] prefixed

Parameter

Explanation

Input type

Default

--output-filename

The output filename of the bundle

The output filename of the bundle string [ name ] .js

Parameter

Explanation

Input type

Default

--output-jsonp-function

The name of the JSONP function used for chunk loading

The name of the JSONP function used for chunk loading string webpackJsonp

Parameter

Explanation

Input type

Default

--output-library

Expose the exports of the entry point as library

Expose the exports of the entry point as library string

Parameter

Explanation

Input type

Default

--output-library-target

The type for exposing the exports of the entry point as library

The type for exposing the exports of the entry point as library string var

Parameter

Explanation

Input type

Default

--output-path

The output path for compilation assets

The output path for compilation assets string Current directory

Parameter

Explanation

Input type

Default

--output-pathinfo

Include a comment with the request for every dependency

Include a comment with the request for every dependency boolean false

Parameter

Explanation

Input type

Default

--output-public-path

The public path for the assets

The public path for the assets string /

Parameter

Explanation

Input type

Default

--output-source-map-filename

The output filename for the SourceMap

The output filename for the SourceMap string [ name ] .map or [ outputFilename ] .map

Parameter

Explanation

Input type

Default

--build-delimiter

Display custom text after build output

Display custom text after build output string Default string is null. You could provide a string such as === Build done ===

Example Usage

webpack index=./src/index.js index2=./src/index2.js --output-path='./dist' --output-filename='[name][hash].bundle.js'

| Asset                                | Size    | Chunks      | Chunk Names   |
|--------------------------------------|---------|-------------|---------------|
| index2740fdca26e9348bedbec.bundle.js |  2.6 kB | 0 [emitted] | index2        |
| index740fdca26e9348bedbec.bundle.js  | 2.59 kB | 1 [emitted] | index         |
	[0] ./src/others.js 29 bytes {0} {1} [built]
	[1] ./src/index.js 51 bytes {1} [built]
	[2] ./src/index2.js 54 bytes {0} [built]
webpack.js index=./src/index.js index2=./src/index2.js --output-path='./dist' --output-filename='[name][hash].bundle.js' --devtool source-map --output-source-map-filename='[name]123.map'

| Asset                                | Size    | Chunks      | Chunk Names   |
|--------------------------------------|---------|-------------|---------------|
| index2740fdca26e9348bedbec.bundle.js | 2.76 kB | 0 [emitted] | index2        |
|  index740fdca26e9348bedbec.bundle.js | 2.74 kB | 1 [emitted] | index         |
|                        index2123.map | 2.95 kB | 0 [emitted] | index2        |
|                         index123.map | 2.95 kB | 1 [emitted] | index         |
	[0] ./src/others.js 29 bytes {0} {1} [built]
	[1] ./src/index.js 51 bytes {1} [built]
	[2] ./src/index2.js 54 bytes {0} [built]

Debug Options

This set of options allows you to better debug the application containing assets compiled with webpack

Parameter Explanation Input type Default value

Parameter

Explanation

Input type

Default value

--debug

Switch loaders to debug mode

Switch loaders to debug mode boolean false

Parameter

Explanation

Input type

Default value

--devtool

Define source map type for the bundled resources

Define source map type for the bundled resources string -

Parameter

Explanation

Input type

Default value

--progress

Print compilation progress in percentage

Print compilation progress in percentage boolean false

Parameter

Explanation

Input type

Default value

--display-error-details

Display details about errors

Display details about errors boolean false

Module Options

These options allow you to bind modules as allowed by webpack

Parameter Explanation Usage

Parameter

Explanation

Usage

--module-bind

Bind a file extension to a loader

Bind a file extension to a loader --module-bind js=babel-loader

Parameter

Explanation

Usage

--module-bind-post

Bind a file extension to a post loader

Bind a file extension to a post loader

Parameter

Explanation

Usage

--module-bind-pre

Bind a file extension to a pre loader

Bind a file extension to a pre loader

Watch Options

These options make the build watch for changes in files of the dependency graph and perform the build again.

Parameter Explanation

Parameter

Explanation

--watch, -w

Watch the filesystem for changes

Watch the filesystem for changes

Parameter

Explanation

--watch-aggregate-timeout

Timeout for gathering changes while watching

Timeout for gathering changes while watching

Parameter

Explanation

--watch-poll

The polling interval for watching (also enable polling)

The polling interval for watching (also enable polling)

Parameter

Explanation

--watch-stdin, --stdin

Exit the process when stdin is closed

Exit the process when stdin is closed

Optimize Options

These options allow you to manipulate optimizations for a production build using webpack

Parameter Explanation Plugin Used

Parameter

Explanation

Plugin Used

--optimize-max-chunks

Try to keep the chunk count below a limit

Try to keep the chunk count below a limit LimitChunkCountPlugin

Parameter

Explanation

Plugin Used

--optimize-min-chunk-size

Try to keep the chunk size above a limit

Try to keep the chunk size above a limit MinChunkSizePlugin

Parameter

Explanation

Plugin Used

--optimize-minimize

Minimize javascript and switches loaders to minimizing

Minimize javascript and switches loaders to minimizing TerserPlugin & LoaderOptionsPlugin

Resolve Options

These allow you to configure the webpack resolver with aliases and extensions.

Parameter Explanation Example

Parameter

Explanation

Example

--resolve-alias

Setup a module alias for resolving

Setup a module alias for resolving --resolve-alias jquery-plugin=jquery.plugin

Parameter

Explanation

Example

--resolve-extensions

Setup extensions that should be used to resolve modules

Setup extensions that should be used to resolve modules --resolve-extensions .es6 .js .ts

Parameter

Explanation

Example

--resolve-loader-alias

Minimize javascript and switches loaders to minimizing

Minimize javascript and switches loaders to minimizing

Stats Options

These options allow webpack to display various stats and style them differently in the console output.

Parameter Explanation Type

Parameter

Explanation

Type

--color, --colors

Force colors on the console [default: enabled for TTY output only]

Force colors on the console [ default: enabled for TTY output only ] boolean

Parameter

Explanation

Type

--no-color, --no-colors

Force no colors on the console

Force no colors on the console boolean

Parameter

Explanation

Type

--display

Select display preset (verbose, detailed, normal, minimal, errors-only, none; since webpack 3.0.0)

Select display preset (verbose, detailed, normal, minimal, errors-only, none; since webpack 3.0.0) string

Parameter

Explanation

Type

--display-cached

Display also cached modules in the output

Display also cached modules in the output boolean

Parameter

Explanation

Type

--display-cached-assets

Display also cached assets in the output

Display also cached assets in the output boolean

Parameter

Explanation

Type

--display-chunks

Display chunks in the output

Display chunks in the output boolean

Parameter

Explanation

Type

--display-depth

Display distance from entry point for each module

Display distance from entry point for each module boolean

Parameter

Explanation

Type

--display-entrypoints

Display entry points in the output

Display entry points in the output boolean

Parameter

Explanation

Type

--display-error-details

Display details about errors

Display details about errors boolean

Parameter

Explanation

Type

--display-exclude

Exclude modules in the output

Exclude modules in the output boolean

Parameter

Explanation

Type

--display-max-modules

Set the maximum number of visible modules in output

Set the maximum number of visible modules in output number

Parameter

Explanation

Type

--display-modules

Display even excluded modules in the output

Display even excluded modules in the output boolean

Parameter

Explanation

Type

--display-optimization-bailout

Scope hoisting fallback trigger (since webpack 3.0.0)

Scope hoisting fallback trigger (since webpack 3.0.0) boolean

Parameter

Explanation

Type

--display-origins

Display origins of chunks in the output

Display origins of chunks in the output boolean

Parameter

Explanation

Type

--display-provided-exports

Display information about exports provided from modules

Display information about exports provided from modules boolean

Parameter

Explanation

Type

--display-reasons

Display reasons about module inclusion in the output

Display reasons about module inclusion in the output boolean

Parameter

Explanation

Type

--display-used-exports

Display information about used exports in modules (Tree Shaking)

Display information about used exports in modules (Tree Shaking) boolean

Parameter

Explanation

Type

--hide-modules

Hide info about modules

Hide info about modules boolean

Parameter

Explanation

Type

--sort-assets-by

Sort the assets list by property in asset

Sort the assets list by property in asset string

Parameter

Explanation

Type

--sort-chunks-by

Sort the chunks list by property in chunk

Sort the chunks list by property in chunk string

Parameter

Explanation

Type

--sort-modules-by

Sort the modules list by property in module

Sort the modules list by property in module string

Parameter

Explanation

Type

--verbose

Show more details

Show more details boolean

Advanced Options

Parameter Explanation Usage

Parameter

Explanation

Usage

--bail

Abort the compilation on first error

Abort the compilation on first error

Parameter

Explanation

Usage

--cache

Enable in memory caching [Enabled by default for watch]

Enable in memory caching [ Enabled by default for watch ] --cache=false

Parameter

Explanation

Usage

--define

Define any free variable, see shimming

Define any free variable, see shimming --define process.env.NODE_ENV="'development'"

Parameter

Explanation

Usage

Enables Hot Module Replacement --hot=true

Parameter

Explanation

Usage

--labeled-modules

Enables labeled modules [Uses LabeledModulesPlugin]

Enables labeled modules [ Uses LabeledModulesPlugin ]

Parameter

Explanation

Usage

--live-reload

Enables live reloading

Enables live reloading --live-reload=true

Parameter

Explanation

Usage

--plugin

Load this plugin

Load this plugin

Parameter

Explanation

Usage

--prefetch

Prefetch the particular file

Prefetch the particular file --prefetch=./files.js

Parameter

Explanation

Usage

--provide

Provide these modules as globals, see shimming

Provide these modules as globals, see shimming --provide jQuery=jquery

Parameter

Explanation

Usage

--records-input-path

Path to the records file (reading)

Path to the records file (reading)

Parameter

Explanation

Usage

--records-output-path

Path to the records file (writing)

Path to the records file (writing)

Parameter

Explanation

Usage

--records-path

Path to the records file

Path to the records file

Parameter

Explanation

Usage

--target

The targeted execution environment

The targeted execution environment --target='node'

Shortcuts

Shortcut Replaces

Shortcut

Replaces

-d

--debug --devtool cheap-module-eval-source-map --output-pathinfo

--debug --devtool cheap-module-eval-source-map --output-pathinfo

Shortcut

Replaces

-p

--optimize-minimize --define process.env.NODE_ENV="production", see building for production

--optimize-minimize --define process.env.NODE_ENV="production" , see building for production

Profiling

The --profile option captures timing information for each step of the compilation and includes this in the output.

webpack --profile

⋮
[0] ./src/index.js 90 bytes {0} [built]
    factory:22ms building:16ms = 38ms

For each module, the following details are included in the output as applicable:

  • factory: time to collect module metadata (e.g. resolving the filename)
  • building: time to build the module (e.g. loaders and parsing)
  • dependencies: time to identify and connect the module’s dependencies

Paired with --progress, --profile gives you an in-depth idea of which step in the compilation is taking how long. This can help you optimize your build in a more informed manner.

webpack --progress --profile

30ms building modules
1ms sealing
1ms optimizing
0ms basic module optimization
1ms module optimization
1ms advanced module optimization
0ms basic chunk optimization
0ms chunk optimization
1ms advanced chunk optimization
0ms module and chunk tree optimization
1ms module reviving
0ms module order optimization
1ms module id optimization
1ms chunk reviving
0ms chunk order optimization
1ms chunk id optimization
10ms hashing
0ms module assets processing
13ms chunk assets processing
1ms additional chunk assets processing
0ms recording
0ms additional asset processing
26ms chunk asset optimization
1ms asset optimization
6ms emitting
⋮

Node Interface

webpack provides a Node.js API which can be used directly in Node.js runtime.

The Node.js API is useful in scenarios in which you need to customize the build or development process since all the reporting and error handling must be done manually and webpack only does the compiling part. For this reason the stats configuration options will not have any effect in the webpack() call.

Installation

To start using the webpack Node.js API, first install webpack if you haven’t yet:

npm install --save-dev webpack

Then require the webpack module in your Node.js script:

const webpack = require('webpack');

Or if you prefer ES2015:

import webpack from 'webpack';

webpack()

The imported webpack function is fed a webpack Configuration Object and runs the webpack compiler if a callback function is provided:

const webpack = require('webpack');

webpack({
  // [Configuration Object](/configuration/)
}, (err, stats) => { // [Stats Object](#stats-object)
  if (err || stats.hasErrors()) {
    // [Handle errors here](#error-handling)
  }
  // Done processing
});

The err object will not include compilation errors. Those must be handled separately using stats.hasErrors(), which will be covered in detail in the Error Handling section of this guide. The err object will only contain webpack-related issues, such as misconfiguration, etc.

You can provide the webpack function with an array of configurations. See the MultiCompiler section below for more information.

Compiler Instance

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. The Compiler instance provides the following methods:

  • .run(callback)
  • .watch(watchOptions, handler)

Typically, only one master Compiler instance is created, although child compilers can be created in order to delegate specific tasks. The Compiler is ultimately just a function which performs bare minimum functionality to keep a lifecycle running. It delegates all the loading, bundling, and writing work to registered plugins.

The hooks property on a Compiler instance is used to register a plugin to any hook event in the Compiler's lifecycle. The WebpackOptionsDefaulter and WebpackOptionsApply utilities are used by webpack to configure its Compiler instance with all the built-in plugins.

The run method is then used to kickstart all compilation work. Upon completion, the given callback function is executed. The final logging of stats and errors should be done in this callback function.

The API only supports a single concurrent compilation at a time. When using run, wait for it to finish before calling run or watch again. When using watch, call close and wait for it to finish before calling run or watch again. Concurrent compilations will corrupt the output files.

Run

Calling the run method on the Compiler instance is much like the quick run method mentioned above:

const webpack = require('webpack');

const compiler = webpack({
  // [Configuration Object](/configuration/)
});

compiler.run((err, stats) => { // [Stats Object](#stats-object)
  // ...
});

Watching

Calling the watch method triggers the webpack runner, but then watches for changes (much like CLI: webpack --watch), as soon as webpack detects a change, runs again. Returns an instance of Watching.

watch(watchOptions, callback);
const webpack = require('webpack');

const compiler = webpack({
  // [Configuration Object](/configuration/)
});

const watching = compiler.watch({
  // Example [watchOptions](/configuration/watch/#watchoptions)
  aggregateTimeout: 300,
  poll: undefined
}, (err, stats) => { // [Stats Object](#stats-object)
  // Print watch/build result here...
  console.log(stats);
});

Watching options are covered in detail here.

Filesystem inaccuracies may trigger multiple builds for a single change. So, in the example above, the console.log statement may fire multiple times for a single modification. Users should expect this behavior and may check stats.hash to see if the file hash has actually changed.

Close Watching

The watch method returns a Watching instance that exposes .close(callback) method. Calling this method will end watching:

watching.close(() => {
  console.log('Watching Ended.');
});

It’s not allowed to watch or run again before the existing watcher has been closed or invalidated.

Invalidate Watching

Using watching.invalidate, you can manually invalidate the current compiling round, without stopping the watch process:

watching.invalidate();

Stats Object

The stats object that is passed as a second argument of the webpack() callback, is a good source of information about the code compilation process. It includes:

  • Errors and Warnings (if any)
  • Timings
  • Module and Chunk information

The webpack CLI uses this information to display nicely formatted output in your console.

When using the MultiCompiler, a MultiStats instance is returned that fulfills the same interface as stats, i.e. the methods described below.

This stats object exposes the following methods:

stats.hasErrors()

Can be used to check if there were errors while compiling. Returns true or false.

stats.hasWarnings()

Can be used to check if there were warnings while compiling. Returns true or false.

stats.toJson(options)

Returns compilation information as a JSON object. options can be either a string (a preset) or an object for more granular control:

stats.toJson('minimal'); // [more options: 'verbose', etc](/configuration/stats).
stats.toJson({
  assets: false,
  hash: true
});

All available options and presets are described in the stats documentation.

Here’s an example of this function’s output.

stats.toString(options)

Returns a formatted string of the compilation information (similar to CLI output).

Options are the same as stats.toJson(options) with one addition:

stats.toString({
  // Add console colors
  colors: true
});

Here’s an example of stats.toString() usage:

const webpack = require('webpack');

webpack({
  // [Configuration Object](/configuration/)
}, (err, stats) => {
  if (err) {
    console.error(err);
    return;
  }

  console.log(stats.toString({
    chunks: false,  // Makes the build much quieter
    colors: true    // Shows colors in the console
  }));
});

MultiCompiler

The MultiCompiler module allows webpack to run multiple configurations in separate compilers. If the options parameter in the webpack's NodeJS api is an array of options, webpack applies separate compilers and calls the callback after all compilers have been executed.

var webpack = require('webpack');

webpack([
  { entry: './index1.js', output: { filename: 'bundle1.js' } },
  { entry: './index2.js', output: { filename: 'bundle2.js' } }
], (err, stats) => { // [Stats Object](#stats-object)
  process.stdout.write(stats.toString() + '\\n');
})

Multiple configurations will not be run in parallel. Each configuration is only processed after the previous one has finished processing. To process them in parallel, you can use a third-party solution like parallel-webpack.

Error Handling

For a good error handling, you need to account for these three types of errors:

  • Fatal webpack errors (wrong configuration, etc)
  • Compilation errors (missing modules, syntax errors, etc)
  • Compilation warnings

Here’s an example that does all that:

const webpack = require('webpack');

webpack({
  // [Configuration Object](/configuration/)
}, (err, stats) => {
  if (err) {
    console.error(err.stack || err);
    if (err.details) {
      console.error(err.details);
    }
    return;
  }

  const info = stats.toJson();

  if (stats.hasErrors()) {
    console.error(info.errors);
  }

  if (stats.hasWarnings()) {
    console.warn(info.warnings);
  }

  // Log result...
});

Custom File Systems

By default, webpack reads files and writes files to disk using a normal file system. However, it is possible to change the input or output behavior using a different kind of file system (memory, webDAV, etc). To accomplish this, one can change the inputFileSystem or outputFileSystem. For example, you can replace the default outputFileSystem with memory-fs to write files to memory instead of to disk:

const MemoryFS = require('memory-fs');
const webpack = require('webpack');

const fs = new MemoryFS();
const compiler = webpack({ /* options */ });

compiler.outputFileSystem = fs;
compiler.run((err, stats) => {
  // Read the output later:
  const content = fs.readFileSync('...');
});

Note that this is what webpack-dev-middleware, used by webpack-dev-server and many other packages, uses to mysteriously hide your files but continue serving them up to the browser!

The output file system you provide needs to be compatible with Node’s own fs interface, which requires the mkdirp and join helper methods.

Stats Data

When compiling source code with webpack, users can generate a JSON file containing statistics about modules. These statistics can be used to analyze an application's dependency graph as well as to optimize compilation speed. The file is typically generated with the following CLI command:

webpack --profile --json > compilation-stats.json

The --json > compilation-stats.json flag indicates to webpack that it should emit the compilation-stats.json containing the dependency graph and various other build information. Typically, the --profile flag is also added so that a profile section is added to each modules object containing module-specific compilation stats.

Structure

The top-level structure of the output JSON file is fairly straightforward but there are a few nested data structures as well. Each nested structure has a dedicated section below to make this document more consumable. Note that you can click links within the top-level structure below to jump to relevant sections and documentation:

{
  'version': '1.4.13', // Version of webpack used for the compilation
  'hash': '11593e3b3ac85436984a', // Compilation specific hash
  'time': 2469, // Compilation time in milliseconds
  'filteredModules': 0, // A count of excluded modules when [`exclude`](/configuration/stats/#stats) is passed to the [`toJson`](/api/node/#statstojsonoptions) method
  'outputPath': '/', // path to webpack output directory
  'assetsByChunkName': {
    // Chunk name to emitted asset(s) mapping
    'main': 'web.js?h=11593e3b3ac85436984a',
    'named-chunk': 'named-chunk.web.js',
    'other-chunk': [
      'other-chunk.js',
      'other-chunk.css'
    ]
  },
  'assets': [
    // A list of [asset objects](#asset-objects)
  ],
  'chunks': [
    // A list of [chunk objects](#chunk-objects)
  ],
  'modules': [
    // A list of [module objects](#module-objects)
  ],
  'errors': [
    // A list of [error strings](#errors-and-warnings)
  ],
  'warnings': [
    // A list of [warning strings](#errors-and-warnings)
  ]
}

Asset Objects

Each assets object represents an output file emitted from the compilation. They all follow a similar structure:

{
  'chunkNames': [], // The chunks this asset contains
  'chunks': [ 10, 6 ], // The chunk IDs this asset contains
  'emitted': true, // Indicates whether or not the asset made it to the `output` directory
  'name': '10.web.js', // The `output` filename
  'size': 1058, // The size of the file in bytes
  'info': {
    'immutable': true, // A flag telling whether the asset can be long term cached (contains a hash)
    'size': 1058, // The size in bytes, only becomes available after asset has been emitted
    'development': true, // A flag telling whether the asset is only used for development and doesn't count towards user-facing assets
    'hotModuleReplacement': true // A flag telling whether the asset ships data for updating an existing application (HMR)
  }
}

Asset's info property is available since webpack v4.40.0

Chunk Objects

Each chunks object represents a group of modules known as a chunk. Each object follows the following structure:

{
  "entry": true, // Indicates whether or not the chunk contains the webpack runtime
  "files": [
    // An array of filename strings that contain this chunk
  ],
  "filteredModules": 0, // See the description in the [top-level structure](#structure) above
  "id": 0, // The ID of this chunk
  "initial": true, // Indicates whether this chunk is loaded on initial page load or [on demand](/guides/lazy-loading)
  "modules": [
    // A list of [module objects](#module-objects)
    "web.js?h=11593e3b3ac85436984a"
  ],
  "names": [
    // An list of chunk names contained within this chunk
  ],
  "origins": [
    // See the description below...
  ],
  "parents": [], // Parent chunk IDs
  "rendered": true, // Indicates whether or not the chunk went through Code Generation
  "size": 188057 // Chunk size in bytes
}

The chunks object will also contain a list of origins describing how the given chunk originated. Each origins object follows the following schema:

{
  "loc": "", // Lines of code that generated this chunk
  "module": "(webpack)\\test\\browsertest\\lib\\index.web.js", // Path to the module
  "moduleId": 0, // The ID of the module
  "moduleIdentifier": "(webpack)\\test\\browsertest\\lib\\index.web.js", // Path to the module
  "moduleName": "./lib/index.web.js", // Relative path to the module
  "name": "main", // The name of the chunk
  "reasons": [
    // A list of the same `reasons` found in [module objects](#module-objects)
  ]
}

Module Objects

What good would these statistics be without some description of the compiled application's actual modules? Each module in the dependency graph is represented by the following structure:

{
  "assets": [
    // A list of [asset objects](#asset-objects)
  ],
  "built": true, // Indicates that the module went through [Loaders](/concepts/loaders), Parsing, and Code Generation
  "cacheable": true, // Whether or not this module is cacheable
  "chunks": [
    // IDs of chunks that contain this module
  ],
  "errors": 0, // Number of errors when resolving or processing the module
  "failed": false, // Whether or not compilation failed on this module
  "id": 0, // The ID of the module (analogous to [`module.id`](/api/module-variables/#moduleid-commonjs))
  "identifier": "(webpack)\\test\\browsertest\\lib\\index.web.js", // A unique ID used internally
  "name": "./lib/index.web.js", // Path to the actual file
  "optional": false, // All requests to this module are with `try... catch` blocks (irrelevant with ESM)
  "prefetched": false, // Indicates whether or not the module was [prefetched](/plugins/prefetch-plugin)
  "profile": {
    // Module specific compilation stats corresponding to the [`--profile` flag](/api/cli/#profiling) (in milliseconds)
    "building": 73, // Loading and parsing
    "dependencies": 242, // Building dependencies
    "factory": 11 // Resolving dependencies
  },
  "reasons": [
    // See the description below...
  ],
  "size": 3593, // Estimated size of the module in bytes
  "source": "// Should not break it...\r\nif(typeof...", // The stringified raw source
  "warnings": 0 // Number of warnings when resolving or processing the module
}

Every module also contains a list of reasons objects describing why that module was included in the dependency graph. Each "reason" is similar to the origins seen above in the chunk objects section:

{
  "loc": "33:24-93", // Lines of code that caused the module to be included
  "module": "./lib/index.web.js", // Relative path to the module based on [context](/configuration/entry-context/#context)
  "moduleId": 0, // The ID of the module
  "moduleIdentifier": "(webpack)\\test\\browsertest\\lib\\index.web.js", // Path to the module
  "moduleName": "./lib/index.web.js", // A more readable name for the module (used for "pretty-printing")
  "type": "require.context", // The [type of request](/api/module-methods) used
  "userRequest": "../../cases" // Raw string used for the `import` or `require` request
}

Errors and Warnings

The errors and warnings properties each contain a list of strings. Each string contains a message and stack trace:

../cases/parsing/browserify/index.js
Critical dependencies:
2:114-121 This seem to be a pre-built javascript file. Even while this is possible, it's not recommended. Try to require to original source to get better results.
 @ ../cases/parsing/browserify/index.js 2:114-121

Note that the stack traces are removed when errorDetails: false is passed to the toJson method. The errorDetails option is set to true by default.

Hot Module Replacement

If Hot Module Replacement has been enabled via the HotModuleReplacementPlugin, its interface will be exposed under the module.hot property. Typically, users will check to see if the interface is accessible, then begin working with it. As an example, here's how you might accept an updated module:

if (module.hot) {
  module.hot.accept('./library.js', function() {
    // Do something with the updated library module...
  });
}

The following methods are supported...

Module API

accept

Accept updates for the given dependencies and fire a callback to react to those updates.

module.hot.accept(
  dependencies, // Either a string or an array of strings
  callback // Function to fire when the dependencies are updated
);

When using ESM import all imported symbols from dependencies are automatically updated. Note: The dependency string must match exactly with the from string in the import. In some cases callback can even be omitted. Using require() in the callback doesn't make sense here.

When using CommonJS you need to update dependencies manually by using require() in the callback. Omitting the callback doesn't make sense here.

accept (self)

Accept updates for itself.

module.hot.accept(
  errorHandler // Function to handle errors when evaluating the new version
);

When this module or dependencies are updated, this module can be disposed and re-evaluated without informing parents. This makes sense if this module has no exports (or exports are updated in another way).

The errorHandler is fired when the evaluation of this module (or dependencies) has thrown an exception.

decline

Reject updates for the given dependencies forcing the update to fail with a 'decline' code.

module.hot.decline(
  dependencies // Either a string or an array of strings
);

Flag a dependency as not-update-able. This makes sense when changing exports of this dependency can be handled or handling is not implemented yet. Depending on your HMR management code an update to these dependencies (or unaccepted dependencies of it) usually causes a full-reload of the page.

decline (self)

Reject updates for itself.

module.hot.decline();

Flag this module as not-update-able. This makes sense when this module has irreversible side-effects, or HMR handling is not implemented for this module yet. Depending on your HMR management code an update to this module (or unaccepted dependencies) usually causes a full-reload of the page.

dispose (or addDisposeHandler)

Add a handler which is executed when the current module code is replaced. This should be used to remove any persistent resource you have claimed or created. If you want to transfer state to the updated module, add it to the given data parameter. This object will be available at module.hot.data after the update.

module.hot.dispose(data => {
  // Clean up and pass data to the updated module...
});

removeDisposeHandler

Remove the handler added via dispose or addDisposeHandler.

module.hot.removeDisposeHandler(callback);

Management API

status

Retrieve the current status of the hot module replacement process.

module.hot.status(); // Will return one of the following strings...
Status Description

Status

Description

idle

The process is waiting for a call to check (see below)

The process is waiting for a call to check (see below)

Status

Description

check

The process is checking for updates

The process is checking for updates

Status

Description

prepare

The process is getting ready for the update (e.g. downloading the updated module)

The process is getting ready for the update (e.g. downloading the updated module)

Status

Description

ready

The update is prepared and available

The update is prepared and available

Status

Description

dispose

The process is calling the dispose handlers on the modules that will be replaced

The process is calling the dispose handlers on the modules that will be replaced

Status

Description

apply

The process is calling the accept handlers and re-executing self-accepted modules

The process is calling the accept handlers and re-executing self-accepted modules

Status

Description

abort

An update was aborted, but the system is still in its previous state

An update was aborted, but the system is still in its previous state

Status

Description

fail

An update has thrown an exception and the system's state has been compromised

An update has thrown an exception and the system's state has been compromised

check

Test all loaded modules for updates and, if updates exist, apply them.

module.hot.check(autoApply).then(outdatedModules => {
  // outdated modules...
}).catch(error => {
  // catch errors
});

The autoApply parameter can either be a boolean or options to pass to the apply method when called.

apply

Continue the update process (as long as module.hot.status() === 'ready').

module.hot.apply(options).then(outdatedModules => {
  // outdated modules...
}).catch(error => {
  // catch errors
});

The optional options object can include the following properties:

  • ignoreUnaccepted (boolean): Ignore changes made to unaccepted modules.
  • ignoreDeclined (boolean): Ignore changes made to declined modules.
  • ignoreErrored (boolean): Ignore errors thrown in accept handlers, error handlers and while reevaluating module.
  • onDeclined (function(info)): Notifier for declined modules
  • onUnaccepted (function(info)): Notifier for unaccepted modules
  • onAccepted (function(info)): Notifier for accepted modules
  • onDisposed (function(info)): Notifier for disposed modules
  • onErrored (function(info)): Notifier for errors

The info parameter will be an object containing some of the following values:

{
  type: "self-declined" | "declined" |
        "unaccepted" | "accepted" |
        "disposed" | "accept-errored" |
        "self-accept-errored" | "self-accept-error-handler-errored",
  moduleId: 4, // The module in question.
  dependencyId: 3, // For errors: the module id owning the accept handler.
  chain: [1, 2, 3, 4], // For declined/accepted/unaccepted: the chain from where the update was propagated.
  parentId: 5, // For declined: the module id of the declining parent
  outdatedModules: [1, 2, 3, 4], // For accepted: the modules that are outdated and will be disposed
  outdatedDependencies: { // For accepted: The location of accept handlers that will handle the update
    5: [4]
  },
  error: new Error(...), // For errors: the thrown error
  originalError: new Error(...) // For self-accept-error-handler-errored:
                                // the error thrown by the module before the error handler tried to handle it.
}

addStatusHandler

Register a function to listen for changes in status.

module.hot.addStatusHandler(status => {
  // React to the current status...
});

removeStatusHandler

Remove a registered status handler.

module.hot.removeStatusHandler(callback);

Loader Interface

A loader is just a JavaScript module that exports a function. The loader runner calls this function and passes the result of the previous loader or the resource file into it. The this context of the function is filled-in by webpack and the loader runner with some useful methods that allow the loader (among other things) to change its invocation style to async, or get query parameters.

The first loader is passed one argument: the content of the resource file. The compiler expects a result from the last loader. The result should be a String or a Buffer (which is converted to a string), representing the JavaScript source code of the module. An optional SourceMap result (as a JSON object) may also be passed.

A single result can be returned in sync mode. For multiple results the this.callback() must be called. In async mode this.async() must be called to indicate that the loader runner should wait for an asynchronous result. It returns this.callback(). Then the loader must return undefined and call that callback.

Examples

The following sections provide some basic examples of the different types of loaders. Note that the map and meta parameters are optional, see this.callback below.

Synchronous Loaders

Either return or this.callback can be used to return the transformed content synchronously:

sync-loader.js

module.exports = function(content, map, meta) {
  return someSyncOperation(content);
};

The this.callback method is more flexible as it allows multiple arguments to be passed as opposed to just the content.

sync-loader-with-multiple-results.js

module.exports = function(content, map, meta) {
  this.callback(null, someSyncOperation(content), map, meta);
  return; // always return undefined when calling callback()
};

Asynchronous Loaders

For asynchronous loaders, this.async is used to retrieve the callback function:

async-loader.js

module.exports = function(content, map, meta) {
  var callback = this.async();
  someAsyncOperation(content, function(err, result) {
    if (err) return callback(err);
    callback(null, result, map, meta);
  });
};

async-loader-with-multiple-results.js

module.exports = function(content, map, meta) {
  var callback = this.async();
  someAsyncOperation(content, function(err, result, sourceMaps, meta) {
    if (err) return callback(err);
    callback(null, result, sourceMaps, meta);
  });
};

Loaders were originally designed to work in synchronous loader pipelines, like Node.js (using enhanced-require), and asynchronous pipelines, like in webpack. However, since expensive synchronous computations are a bad idea in a single-threaded environment like Node.js, we advise making your loader asynchronous if possible. Synchronous loaders are ok if the amount of computation is trivial.

"Raw" Loader

By default, the resource file is converted to a UTF-8 string and passed to the loader. By setting the raw flag, the loader will receive the raw Buffer. Every loader is allowed to deliver its result as String or as Buffer. The compiler converts them between loaders.

raw-loader.js

module.exports = function(content) {
  assert(content instanceof Buffer);
  return someSyncOperation(content);
  // return value can be a `Buffer` too
  // This is also allowed if loader is not "raw"
};
module.exports.raw = true;

Pitching Loader

Loaders are always called from right to left. There are some instances where the loader only cares about the metadata behind a request and can ignore the results of the previous loader. The pitch method on loaders is called from left to right before the loaders are actually executed (from right to left).

Loaders may be added inline in requests and disabled via inline prefixes, which will impact the order in which they are "pitched" and executed. See Rule.enforce for more details.

For the following configuration of use:

module.exports = {
  //...
  module: {
    rules: [
      {
        //...
        use: [
          'a-loader',
          'b-loader',
          'c-loader'
        ]
      }
    ]
  }
};

These steps would occur:

|- a-loader `pitch`
  |- b-loader `pitch`
    |- c-loader `pitch`
      |- requested module is picked up as a dependency
    |- c-loader normal execution
  |- b-loader normal execution
|- a-loader normal execution

So why might a loader take advantage of the "pitching" phase?

First, the data passed to the pitch method is exposed in the execution phase as well under this.data and could be useful for capturing and sharing information from earlier in the cycle.

module.exports = function(content) {
  return someSyncOperation(content, this.data.value);
};

module.exports.pitch = function(remainingRequest, precedingRequest, data) {
  data.value = 42;
};

Second, if a loader delivers a result in the pitch method, the process turns around and skips the remaining loaders. In our example above, if the b-loaders pitch method returned something:

module.exports = function(content) {
  return someSyncOperation(content);
};

module.exports.pitch = function(remainingRequest, precedingRequest, data) {
  if (someCondition()) {
    return 'module.exports = require(' + JSON.stringify('-!' + remainingRequest) + ');';
  }
};

The steps above would be shortened to:

|- a-loader `pitch`
  |- b-loader `pitch` returns a module
|- a-loader normal execution

See the bundle-loader for a good example of how this process can be used in a more meaningful way.

The Loader Context

The loader context represents the properties that are available inside of a loader assigned to the this property.

Given the following example, this require call is used:

In /abc/file.js:

require('./loader1?xyz!loader2!./resource?rrr');

this.version

Loader API version. Currently 2. This is useful for providing backwards compatibility. Using the version you can specify custom logic or fallbacks for breaking changes.

this.context

The directory of the module. Can be used as a context for resolving other stuff.

In the example: /abc because resource.js is in this directory

this.rootContext

Starting with webpack 4, the formerly this.options.context is provided as this.rootContext.

this.request

The resolved request string.

In the example: "/abc/loader1.js?xyz!/abc/node_modules/loader2/index.js!/abc/resource.js?rrr"

this.query

  1. If the loader was configured with an options object, this will point to that object.
  2. If the loader has no options, but was invoked with a query string, this will be a string starting with ?.

Use the getOptions method from loader-utils to extract given loader options.

this.callback

A function that can be called synchronously or asynchronously in order to return multiple results. The expected arguments are:

this.callback(
  err: Error | null,
  content: string | Buffer,
  sourceMap?: SourceMap,
  meta?: any
);
  1. The first argument must be an Error or null
  2. The second argument is a string or a Buffer.
  3. Optional: The third argument must be a source map that is parsable by this module.
  4. Optional: The fourth option, ignored by webpack, can be anything (e.g. some metadata).

It can be useful to pass an abstract syntax tree (AST), like ESTree, as the fourth argument (meta) to speed up the build time if you want to share common ASTs between loaders.

In case this function is called, you should return undefined to avoid ambiguous loader results.

this.async

Tells the loader-runner that the loader intends to call back asynchronously. Returns this.callback.

this.data

A data object shared between the pitch and the normal phase.

this.cacheable

A function that sets the cacheable flag:

cacheable(flag = true: boolean)

By default, loader results are flagged as cacheable. Call this method passing false to make the loader's result not cacheable.

A cacheable loader must have a deterministic result when inputs and dependencies haven't changed. This means the loader shouldn't have dependencies other than those specified with this.addDependency.

this.loaders

An array of all the loaders. It is writable in the pitch phase.

loaders = [{request: string, path: string, query: string, module: function}]

In the example:

[
  {
    request: '/abc/loader1.js?xyz',
    path: '/abc/loader1.js',
    query: '?xyz',
    module: [Function]
  },
  {
    request: '/abc/node_modules/loader2/index.js',
    path: '/abc/node_modules/loader2/index.js',
    query: '',
    module: [Function]
  }
];

this.loaderIndex

The index in the loaders array of the current loader.

In the example: in loader1: 0, in loader2: 1

this.resource

The resource part of the request, including query.

In the example: "/abc/resource.js?rrr"

this.resourcePath

The resource file.

In the example: "/abc/resource.js"

this.resourceQuery

The query of the resource.

In the example: "?rrr"

this.target

Target of compilation. Passed from configuration options.

Example values: "web", "node"

this.webpack

This boolean is set to true when this is compiled by webpack.

Loaders were originally designed to also work as Babel transforms. Therefore, if you write a loader that works for both, you can use this property to know if there is access to additional loaderContext and webpack features.

this.sourceMap

Tells if source map should be generated. Since generating source maps can be an expensive task, you should check if source maps are actually requested.

this.emitWarning

emitWarning(warning: Error)

Emit a warning that will be displayed in the output like the following:

WARNING in ./src/lib.js (./src/loader.js!./src/lib.js)
Module Warning (from ./src/loader.js):
Here is a Warning!
 @ ./src/index.js 1:0-25

Note that the warnings will not be displayed if stats.warnings is set to false, or some other omit setting is used to stats such as none or errors-only. See the stats configuration.

this.emitError

emitError(error: Error)

Emit an error that also can be displayed in the output.

ERROR in ./src/lib.js (./src/loader.js!./src/lib.js)
Module Error (from ./src/loader.js):
Here is an Error!
 @ ./src/index.js 1:0-25

Unlike throwing an Error directly, it will NOT interrupt the compilation process of the current module.

this.loadModule

loadModule(request: string, callback: function(err, source, sourceMap, module))

Resolves the given request to a module, applies all configured loaders and calls back with the generated source, the sourceMap and the module instance (usually an instance of NormalModule). Use this function if you need to know the source code of another module to generate the result.

this.resolve

resolve(context: string, request: string, callback: function(err, result: string))

Resolve a request like a require expression.

this.addDependency

addDependency(file: string)
dependency(file: string) // shortcut

Add a file as dependency of the loader result in order to make them watchable. For example, sass-loader, less-loader uses this to recompile whenever any imported css file changes.

this.addContextDependency

addContextDependency(directory: string)

Add a directory as dependency of the loader result.

this.clearDependencies

clearDependencies()

Remove all dependencies of the loader result, even initial dependencies and those of other loaders. Consider using pitch.

this.emitFile

emitFile(name: string, content: Buffer|string, sourceMap: {...})

Emit a file. This is webpack-specific.

this.fs

Access to the compilation's inputFileSystem property.

this.mode

Read in which mode webpack is running.

Possible values: 'production', 'development', 'none'

Deprecated context properties

The usage of these properties is highly discouraged since we are planning to remove them from the context. They are still listed here for documentation purposes.

this.exec

exec(code: string, filename: string)

Execute some code fragment like a module. See this comment for a replacement method if needed.

this.resolveSync

resolveSync(context: string, request: string) -> string

Resolve a request like a require expression.

this.value

Pass values to the next loader. If you know what your result exports if executed as a module, set this value here (as an only element array).

this.inputValue

Passed from the last loader. If you would execute the input argument as a module, consider reading this variable for a shortcut (for performance).

this.options

The options property has been deprecated in webpack 3 and removed in webpack 4.

this.debug

A boolean flag. It is set when in debug mode.

this.minimize

Tells if result should be minimized.

this._compilation

Hacky access to the Compilation object of webpack.

this._compiler

Hacky access to the Compiler object of webpack.

this._module

Hacky access to the Module object being loaded.

Error Reporting

You can report errors from inside a loader by:

  • Using this.emitError. Will report the errors without interrupting module's compilation.
  • Using throw (or other uncaught exception). Throwing an error while a loader is running will cause current module compilation failure.
  • Using callback (in async mode). Pass an error to the callback will also cause module compilation failure.

For example:

./src/index.js

require('./loader!./lib');

Throwing an error from loader:

./src/loader.js

module.exports = function(source) {
  throw new Error('This is a Fatal Error!');
};

Or pass an error to the callback in async mode:

./src/loader.js

module.exports = function(source) {
  const callback = this.async();
  //...
  callback(new Error('This is a Fatal Error!'), source);
};

The module will get bundled like this:

/***/ "./src/loader.js!./src/lib.js":
/*!************************************!*\
  !*** ./src/loader.js!./src/lib.js ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports) {

throw new Error("Module build failed (from ./src/loader.js):\nError: This is a Fatal Error!\n    at Object.module.exports (/workspace/src/loader.js:3:9)");

/***/ })

Then the build output will also display the error (Similar to this.emitError):

ERROR in ./src/lib.js (./src/loader.js!./src/lib.js)
Module build failed (from ./src/loader.js):
Error: This is a Fatal Error!
    at Object.module.exports (/workspace/src/loader.js:2:9)
 @ ./src/index.js 1:0-25

As you can see below, not only error message, but also details about which loader and module are involved:

  • the module path: ERROR in ./src/lib.js
  • the request string: (./src/loader.js!./src/lib.js)
  • the loader path: (from ./src/loader.js)
  • the caller path: @ ./src/index.js 1:0-25

The loader path in the error is displayed since webpack 4.12

All the errors and warnings will be recorded into stats. Please see Stats Data.

Inline matchResource

A new inline request syntax was introduced in webpack v4. Prefixing <match-resource>!=! to a request will set the matchResource for this request.

It is not recommended to use this syntax in application code. Inline request syntax is intended to only be used by loader generated code. Not following this recommendation will make your code webpack-specific and non-standard.

A relative matchResource will resolve relative to the current context of the containing module.

When a matchResource is set, it will be used to match with the module.rules instead of the original resource. This can be useful if further loaders should be applied to the resource, or if the module type needs to be changed. It's also displayed in the stats and used for matching Rule.issuer and test in splitChunks.

Example:

file.js

/* STYLE: body { background: red; } */
console.log('yep');

A loader could transform the file into the following file and use the matchResource to apply the user-specified CSS processing rules:

file.js (transformed by loader)

import './file.js.css!=!extract-style-loader/getStyles!./file.js';
console.log('yep');

This will add a dependency to extract-style-loader/getStyles!./file.js and treat the result as file.js.css. Because module.rules has a rule matching /\.css$/ and it will apply to this dependency.

The loader could look like this:

extract-style-loader/index.js

const stringifyRequest = require('loader-utils').stringifyRequest;
const getRemainingRequest = require('loader-utils').getRemainingRequest;
const getStylesLoader = require.resolve('./getStyle');

module.exports = function (source) {
  if (STYLES_REGEXP.test(source)) {
    source = source.replace(STYLES_REGEXP, '');
    const remReq = getRemainingRequest(this);
    return `import ${stringifyRequest(`${this.resource}.css!=!${getStylesLoader}!${remReq}`)};${source}`;
  }
  return source;
};

extract-style-loader/getStyles.js

module.exports = function(source) {
  const match = STYLES_REGEXP.match(source);
  return match[0];
};

Logging

Logging API is available since the release of webpack 4.37. When logging is enabled in stats configuration and/or when infrastructure logging is enabled, loaders may log messages which will be printed out in the respective logger format (stats, infrastructure).

  • Loaders should prefer to use this.getLogger() for logging which is a shortcut to compilation.getLogger() with loader path and processed file. This kind of logging is stored to the Stats and formatted accordingly. It can be filtered and exported by the webpack user.
  • Loaders may use this.getLogger('name') to get an independent logger with a child name. Loader path and processed file is still added.
  • Loaders may use special fallback logic for detecting logging support this.getLogger() ? this.getLogger() : console to provide a fallback when an older webpack version is used which does not support getLogger method.

Logger Interface

Available since webpack 4.39.0

Logging output is an additional way to display messages to the end users.

webpack logger is available to loaders and plugins. Emitting as part of the Stats and configured by the user in webpack configuration.

Benefits of custom logging API in webpack:

  • Common place to configure the logging display level
  • Logging output exportable as part of the stats.json
  • Stats presets affect logging output
  • Plugins can affect logging capturing and display level
  • When using multiple plugins and loaders they use a common logging solution
  • CLI, UI tools for webpack may choose different ways to display logging
  • webpack core can emit logging output, e.g. timing data

By introducing webpack logging API we hope to unify the way webpack plugins and loaders emit logging messages and allow better ways to inspect build problems. Integrated logging solution supports plugins and loaders developers by improving their development experience. Paves the way for non-CLI webpack solutions like dashboards or other UIs.

Avoid noise in the log! Keep in mind that multiple plugins and loaders are used together. Loaders are usually processing multiple files and are invoked for every file. Choose logging level as low as possible to keep the log output informative.

Logger methods

  • logger.error(...): for error messages
  • logger.warn(...): for warnings
  • logger.info(...): for important information messages. These messages are displayed by default. Only use this for messages that the user really needs to see
  • logger.log(...): for unimportant information messages. These messages are displayed only when user had opted-in to see them
  • logger.debug(...): for debugging information. These messages are displayed only when user had opted-in to see debug logging for specific modules
  • logger.trace(): to display a stack trace. Displayed like logger.debug
  • logger.group(...): to group messages together. Displayed collapsed like logger.log
  • logger.groupEnd(): to end a logging group
  • logger.groupCollapsed(...): to group messages together. Displayed collapsed like logger.log. Displayed expanded when logging level is set to 'verbose' or 'debug'.
  • logger.status: writes a temporary message, setting a new status, overrides the previous one
  • logger.clear(): to print a horizontal line. Displayed like logger.log
  • logger.profile(...), logger.profileEnd(...): to capture a profile. Delegated to console.profile when supported

Runtime Logger API

Runtime logger API is only intended to be used as a development tool, it is not intended to be included in production mode.

  • const logging = require('webpack/logging/runtime'): to use the logger in runtime, require it directly from webpack
  • logging.getLogger('name'): to get individual logger by name
  • logging.configureDefaultLogger(...): to override the default logger.
const logging = require('webpack/logging/runtime');
logging.configureDefaultLogger({
  level: 'log',
  debug: /something/
});
  • logging.hooks.log: to apply Plugins to the runtime logger

Module Methods

This section covers all methods available in code compiled with webpack. When using webpack to bundle your application, you can pick from a variety of module syntax styles including ES6, CommonJS, and AMD.

While webpack supports multiple module syntaxes, we recommend following a single syntax for consistency and to avoid odd behaviors/bugs. Here's one example of mixing ES6 and CommonJS, but there are surely others.

Version 2 of webpack supports ES6 module syntax natively, meaning you can use import and export without a tool like babel to handle this for you. Keep in mind that you will still probably need babel for other ES6+ features. The following methods are supported by webpack:

import

Statically import the exports of another module.

import MyModule from './my-module.js';
import { NamedExport } from './other-module.js';

The keyword here is statically. A normal import statement cannot be used dynamically within other logic or contain variables. See the spec for more information and import() below for dynamic usage.

export

Export anything as a default or named export.

// Named exports
export var Count = 5;
export function Multiply(a, b) {
  return a * b;
}

// Default export
export default {
  // Some data...
};

import()

function(string path):Promise

Dynamically load modules. Calls to import() are treated as split points, meaning the requested module and its children are split out into a separate chunk.

The ES2015 Loader spec defines import() as method to load ES2015 modules dynamically on runtime.

if ( module.hot ) {
  import('lodash').then(_ => {
    // Do something with lodash (a.k.a '_')...
  });
}

This feature relies on Promise internally. If you use import() with older browsers, remember to shim Promise using a polyfill such as es6-promise or promise-polyfill.

Dynamic expressions in import()

It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.

The import() must contain at least some information about where the module is located. Bundling can be limited to a specific directory or set of files so that when you are using a dynamic expression - every module that could potentially be requested on an import() call is included. For example, import(`./locale/${language}.json`) will cause every .json file in the ./locale directory to be bundled into the new chunk. At run time, when the variable language has been computed, any file like english.json or german.json will be available for consumption.

// imagine we had a method to get language from cookies or other storage
const language = detectVisitorLanguage();
import(`./locale/${language}.json`).then(module => {
  // do something with the translations
});

Using the webpackInclude and webpackExclude options allows you to add regex patterns that reduce the number of files that webpack will bundle for this import.

Magic Comments

Inline comments to make features work. By adding comments to the import, we can do things such as name our chunk or select different modes. For a full list of these magic comments see the code below followed by an explanation of what these comments do.

// Single target
import(
  /* webpackChunkName: "my-chunk-name" */
  /* webpackMode: "lazy" */
  'module'
);

// Multiple possible targets
import(
  /* webpackInclude: /\.json$/ */
  /* webpackExclude: /\.noimport\.json$/ */
  /* webpackChunkName: "my-chunk-name" */
  /* webpackMode: "lazy" */
  /* webpackPrefetch: true */
  /* webpackPreload: true */
  `./locale/${language}`
);
import(/* webpackIgnore: true */ 'ignored-module.js');

webpackIgnore: Disables dynamic import parsing when set to true.

Note that setting webpackIgnore to true opts out of code splitting.

webpackChunkName: A name for the new chunk. Since webpack 2.6.0, the placeholders [index] and [request] are supported within the given string to an incremented number or the actual resolved filename respectively. Adding this comment will cause our separate chunk to be named [my-chunk-name].js instead of [id].js.

webpackMode: Since webpack 2.6.0, different modes for resolving dynamic imports can be specified. The following options are supported:

  • "lazy" (default): Generates a lazy-loadable chunk for each import()ed module.
  • "lazy-once": Generates a single lazy-loadable chunk that can satisfy all calls to import(). The chunk will be fetched on the first call to import(), and subsequent calls to import() will use the same network response. Note that this only makes sense in the case of a partially dynamic statement, e.g. import(`./locales/${language}.json`), where there are multiple module paths that could potentially be requested.
  • "eager": Generates no extra chunk. All modules are included in the current chunk and no additional network requests are made. A Promise is still returned but is already resolved. In contrast to a static import, the module isn't executed until the call to import() is made.
  • "weak": Tries to load the module if the module function has already been loaded in some other way (e.g. another chunk imported it or a script containing the module was loaded). A Promise is still returned, but only successfully resolves if the chunks are already on the client. If the module is not available, the Promise is rejected. A network request will never be performed. This is useful for universal rendering when required chunks are always manually served in initial requests (embedded within the page), but not in cases where app navigation will trigger an import not initially served.

webpackPrefetch: Tells the browser that the resource is probably needed for some navigation in the future. Check out the guide for more information on how webpackPrefetch works.

webpackPreload: Tells the browser that the resource might be needed during the current navigation. Check out the guide for more information on how webpackPreload works.

Note that all options can be combined like so /* webpackMode: "lazy-once", webpackChunkName: "all-i18n-data" */. This is wrapped in a JavaScript object and executed using node VM. You do not need to add curly brackets.

webpackInclude: A regular expression that will be matched against during import resolution. Only modules that match will be bundled.

webpackExclude: A regular expression that will be matched against during import resolution. Any module that matches will not be bundled.

Note that webpackInclude and webpackExclude options do not interfere with the prefix. eg: ./locale.

The use of System.import in webpack did not fit the proposed spec, so it was deprecated in webpack 2.1.0-beta.28 in favor of import().

CommonJS

The goal of CommonJS is to specify an ecosystem for JavaScript outside the browser. The following CommonJS methods are supported by webpack:

require

require(dependency: String);

Synchronously retrieve the exports from another module. The compiler will ensure that the dependency is available in the output bundle.

var $ = require('jquery');
var myModule = require('my-module');

Using it asynchronously may not have the expected effect.

require.resolve

require.resolve(dependency: String);

Synchronously retrieve a module's ID. The compiler will ensure that the dependency is available in the output bundle. See module.id for more information.

Module ID is a number in webpack (in contrast to NodeJS where it is a string -- the filename).

require.cache

Multiple requires of the same module result in only one module execution and only one export. Therefore a cache in the runtime exists. Removing values from this cache causes new module execution and a new export.

This is only needed in rare cases for compatibility!

var d1 = require('dependency');
require('dependency') === d1;
delete require.cache[require.resolve('dependency')];
require('dependency') !== d1;
// in file.js
require.cache[module.id] === module;
require('./file.js') === module.exports;
delete require.cache[module.id];
require.cache[module.id] === undefined;
require('./file.js') !== module.exports; // in theory; in praxis this causes a stack overflow
require.cache[module.id] !== module;

require.ensure

require.ensure() is specific to webpack and superseded by import().

require.ensure(
  dependencies: String[],
  callback: function(require),
  errorCallback: function(error),
  chunkName: String
)

Split out the given dependencies to a separate bundle that will be loaded asynchronously. When using CommonJS module syntax, this is the only way to dynamically load dependencies. Meaning, this code can be run within execution, only loading the dependencies if certain conditions are met.

This feature relies on Promise internally. If you use require.ensure with older browsers, remember to shim Promise using a polyfill such as es6-promise or promise-polyfill.

var a = require('normal-dep');

if ( module.hot ) {
  require.ensure(['b'], function(require) {
    var c = require('c');

    // Do something special...
  });
}

The following parameters are supported in the order specified above:

  • dependencies: An array of strings declaring all modules required for the code in the callback to execute.
  • callback: A function that webpack will execute once the dependencies are loaded. An implementation of the require function is sent as a parameter to this function. The function body can use this to further require() modules it needs for execution.
  • errorCallback: A function that is executed when webpack fails to load the dependencies.
  • chunkName: A name given to the chunk created by this particular require.ensure(). By passing the same chunkName to various require.ensure() calls, we can combine their code into a single chunk, resulting in only one bundle that the browser must load.

Although the implementation of require is passed as an argument to the callback function, using an arbitrary name e.g. require.ensure([], function(request) { request('someModule'); }) isn't handled by webpack's static parser. Use require instead, e.g. require.ensure([], function(require) { require('someModule'); }).

AMD

Asynchronous Module Definition (AMD) is a JavaScript specification that defines an interface for writing and loading modules. The following AMD methods are supported by webpack:

define (with factory)

define([name: String], [dependencies: String[]], factoryMethod: function(...))

If dependencies are provided, factoryMethod will be called with the exports of each dependency (in the same order). If dependencies are not provided, factoryMethod is called with require, exports and module (for compatibility!). If this function returns a value, this value is exported by the module. The compiler ensures that each dependency is available.

Note that webpack ignores the name argument.

define(['jquery', 'my-module'], function($, myModule) {
  // Do something with $ and myModule...

  // Export a function
  return function doSomething() {
    // ...
  };
});

This CANNOT be used in an asynchronous function.

define (with value)

define(value: !Function)

This will simply export the provided value. The value here can be anything except a function.

define({
  answer: 42
});

This CANNOT be used in an async function.

require (amd-version)

require(dependencies: String[], [callback: function(...)])

Similar to require.ensure, this will split the given dependencies into a separate bundle that will be loaded asynchronously. The callback will be called with the exports of each dependency in the dependencies array.

This feature relies on Promise internally. If you use AMD with older browsers (e.g. Internet Explorer 11), remember to shim Promise using a polyfill such as es6-promise or promise-polyfill.

require(['b'], function(b) {
  var c = require('c');
});

There is no option to provide a chunk name.

Labeled Modules

The internal LabeledModulesPlugin enables you to use the following methods for exporting and requiring within your modules:

export label

Export the given value. The label can occur before a function declaration or a variable declaration. The function name or variable name is the identifier under which the value is exported.

export: var answer = 42;
export: function method(value) {
  // Do something...
};

Using it in an async function may not have the expected effect.

require label

Make all exports from the dependency available in the current scope. The require label can occur before a string. The dependency must export values with the export label. CommonJS or AMD modules cannot be consumed.

some-dependency.js

export: var answer = 42;
export: function method(value) {
  // Do something...
};
require: 'some-dependency';
console.log(answer);
method(...);

Webpack

Aside from the module syntaxes described above, webpack also allows a few custom, webpack-specific methods:

require.context

require.context(
  directory: String,
  includeSubdirs: Boolean /* optional, default true */,
  filter: RegExp /* optional, default /^\.\/.*$/, any file */,
  mode: String  /* optional, 'sync' | 'eager' | 'weak' | 'lazy' | 'lazy-once', default 'sync' */
)

Specify a whole group of dependencies using a path to the directory, an option to includeSubdirs, a filter for more fine grained control of the modules included, and a mode to define the way how loading will work. Underlying modules can then be easily resolved later on:

var context = require.context('components', true, /\.html$/);
var componentA = context.resolve('componentA');

If mode is specified as "lazy", the underlying modules will be loaded asynchronously:

var context = require.context('locales', true, /\.json$/, 'lazy');
context('localeA').then(locale => {
  // do something with locale
});

The full list of available modes and its behavior is described in import() documentation.

require.include

require.include(dependency: String)

Include a dependency without executing it. This can be used for optimizing the position of a module in the output chunks.

require.include('a');
require.ensure(['a', 'b'], function(require) { /* ... */ });
require.ensure(['a', 'c'], function(require) { /* ... */ });

This will result in the following output:

  • entry chunk: file.js and a
  • anonymous chunk: b
  • anonymous chunk: c

Without require.include('a') it would be duplicated in both anonymous chunks.

require.resolveWeak

Similar to require.resolve, but this won't pull the module into the bundle. It's what is considered a "weak" dependency.

if(__webpack_modules__[require.resolveWeak('module')]) {
  // Do something when module is available...
}
if(require.cache[require.resolveWeak('module')]) {
  // Do something when module was loaded before...
}

// You can perform dynamic resolves ("context")
// just as with other require/import methods.
const page = 'Foo';
__webpack_modules__[require.resolveWeak(`./page/${page}`)];

require.resolveWeak is the foundation of universal rendering (SSR + Code Splitting), as used in packages such as react-universal-component. It allows code to render synchronously on both the server and initial page-loads on the client. It requires that chunks are manually served or somehow available. It's able to require modules without indicating they should be bundled into a chunk. It's used in conjunction with import() which takes over when user navigation triggers additional imports.

Module Variables

This section covers all variables available in code compiled with webpack. Modules will have access to certain data from the compilation process through module and other variables.

module.loaded (NodeJS)

This is false if the module is currently executing, and true if the sync execution has finished.

module.hot (webpack-specific)

Indicates whether or not Hot Module Replacement is enabled and provides an interface to the process. See the HMR API page for details.

module.id (CommonJS)

The ID of the current module.

module.id === require.resolve('./file.js');

module.exports (CommonJS)

Defines the value that will be returned when a consumer makes a require call to the module (defaults to a new object).

module.exports = function doSomething() {
  // Do something...
};

This CANNOT be used in an asynchronous function.

exports (CommonJS)

This variable is equal to the default value of module.exports (i.e. an object). If module.exports gets overwritten, exports will no longer be exported.

exports.someValue = 42;
exports.anObject = {
  x: 123
};
exports.aFunction = function doSomething() {
  // Do something
};

global (NodeJS)

See node.js global.

process (NodeJS)

See node.js process.

__dirname (NodeJS)

Depending on the config option node.__dirname:

If used inside an expression that is parsed by the Parser, the config option is treated as true.

__filename (NodeJS)

Depending on the config option node.__filename:

If used inside an expression that is parsed by the Parser, the config option is treated as true.

__resourceQuery (webpack-specific)

The resource query of the current module. If the following require call was made, then the query string would be available in file.js.

require('file.js?test');

file.js

__resourceQuery === '?test';

__webpack_public_path__ (webpack-specific)

Equals the config option's output.publicPath.

__webpack_require__ (webpack-specific)

The raw require function. This expression isn't parsed by the Parser for dependencies.

__webpack_chunk_load__ (webpack-specific)

The internal chunk loading function. Takes two arguments:

  • chunkId The id for the chunk to load.
  • callback(require) A callback function called once the chunk is loaded.

__webpack_modules__ (webpack-specific)

Access to the internal object of all modules.

__webpack_hash__ (webpack-specific)

This variable is only available with the HotModuleReplacementPlugin or the ExtendedAPIPlugin. It provides access to the hash of the compilation.

__non_webpack_require__ (webpack-specific)

Generates a require function that is not parsed by webpack. Can be used to do cool stuff with a global require function if available.

DEBUG (webpack-specific)

Equals the config option debug.

Compiler Hooks

The Compiler module is the main engine that creates a compilation instance with all the options passed through the CLI or Node API. It extends the Tapable class in order to register and call plugins. Most user facing plugins are first registered on the Compiler.

This module is exposed as webpack.Compiler and can be used directly. See this example for more information.

When developing a plugin for webpack, you might want to know where each hook is called. To learn this, search for hooks.<hook name>.call across the webpack source

Watching

The Compiler supports watching which monitors the file system and recompiles as files change. When in watch mode, the compiler will emit the additional events such as watchRun, watchClose, and invalid. This is typically used in development, usually under the hood of tools like webpack-dev-server, so that the developer doesn't need to re-compile manually every time. Watch mode can also be entered via the CLI.

Hooks

The following lifecycle hooks are exposed by the compiler and can be accessed as such:

compiler.hooks.someHook.tap('MyPlugin', (params) => {
  /* ... */
});

Depending on the hook type, tapAsync and tapPromise may also be available.

For the description of hook types, see the Tapable docs.

entryOption

SyncBailHook

Called after the entry configuration from webpack options has been processed.

compiler.hooks.entryOption.tap('MyPlugin', (context, entry) => {
  /* ... */
});

Parameters: context, entry

afterPlugins

SyncHook

Called after setting up initial set of internal plugins.

  • Callback Parameters: compiler

afterResolvers

SyncHook

Triggered after resolver setup is complete.

  • Callback Parameters: compiler

environment

SyncHook

Called while preparing the compiler environment, right after inizializing the plugins in the configuration file.

afterEnvironment

SyncHook

Called right after the environment hook, when the compiler environment setup is complete.

beforeRun

AsyncSeriesHook

Adds a hook right before running the compiler.

  • Callback Parameters: compiler

run

AsyncSeriesHook

Hook into the compiler before it begins reading records.

  • Callback Parameters: compiler

watchRun

AsyncSeriesHook

Executes a plugin during watch mode after a new compilation is triggered but before the compilation is actually started.

  • Callback Parameters: compiler

normalModuleFactory

SyncHook

Called after a NormalModuleFactory is created.

  • Callback Parameters: normalModuleFactory

contextModuleFactory

SyncHook

Runs a plugin after a ContextModuleFactory is created.

  • Callback Parameters: contextModuleFactory

beforeCompile

AsyncSeriesHook

Executes a plugin after compilation parameters are created.

  • Callback Parameters: compilationParams

The compilationParams variable is initialized as follows:

compilationParams = {
  normalModuleFactory,
  contextModuleFactory,
  compilationDependencies
};

This hook can be used to add/modify the compilation parameters:

compiler.hooks.beforeCompile.tapAsync('MyPlugin', (params, callback) => {
  params['MyPlugin - data'] = 'important stuff my plugin will use later';
  callback();
});

compile

SyncHook

Called right after beforeCompile, before a new compilation is created.

  • Callback Parameters: compilationParams

thisCompilation

SyncHook

Executed while initializing the compilation, right before emitting the compilation event.

  • Callback Parameters: compilation, compilationParams

compilation

SyncHook

Runs a plugin after a compilation has been created.

  • Callback Parameters: compilation, compilationParams

make

AsyncParallelHook

Executed before finishing the compilation.

  • Callback Parameters: compilation

afterCompile

AsyncSeriesHook

Called after finishing and sealing the compilation.

  • Callback Parameters: compilation

shouldEmit

SyncBailHook

Called before emitting assets. Should return a boolean telling whether to emit.

  • Callback Parameters: compilation
compiler.hooks.shouldEmit.tap('MyPlugin', (compilation) => {
  // return true to emit the output, otherwise false
  return true;
});

emit

AsyncSeriesHook

Executed right before emitting assets to output dir.

  • Callback Parameters: compilation

afterEmit

AsyncSeriesHook

Called after emitting assets to output directory.

  • Callback Parameters: compilation

assetEmitted

AsyncSeriesHook

Allows to get byte content of emitted asset. Available since webpack v4.39.0

  • Callback Parameters: file, content

done

AsyncSeriesHook

Executed when the compilation has completed.

  • Callback Parameters: stats

failed

SyncHook

Called if the compilation fails.

  • Callback Parameters: error

invalid

SyncHook

Executed when a watching compilation has been invalidated.

  • Callback Parameters: fileName, changeTime

watchClose

SyncHook

Called when a watching compilation has stopped.

infrastructureLog

SyncBailHook

Allows to use infrastructure logging when enabled in the configuration via infrastructureLogging option.

  • Callback Parameters: name, type, args

log

SyncBailHook

Allows to log into stats when enabled, see stats.logging, stats.loggingDebug and stats.loggingTrace options.

  • Callback Parameters: origin, logEntry

Compilation Hooks

The Compilation module is used by the Compiler to create new compilations (or builds). A compilation instance has access to all modules and their dependencies (most of which are circular references). It is the literal compilation of all the modules in the dependency graph of an application. During the compilation phase, modules are loaded, sealed, optimized, chunked, hashed and restored.

The Compilation class also extends Tapable and provides the following lifecycle hooks. They can be tapped the same way as compiler hooks:

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

As with the compiler, tapAsync and tapPromise may also be available depending on the type of hook.

buildModule

SyncHook

Triggered before a module build has started, can be used to modify the module.

  • Callback Parameters: module
compilation.hooks.buildModule.tap('SourceMapDevToolModuleOptionsPlugin',
  module => {
    module.useSourceMap = true;
  }
);

rebuildModule

SyncHook

Fired before rebuilding a module.

  • Callback Parameters: module

failedModule

SyncHook

Run when a module build has failed.

  • Callback Parameters: module error

succeedModule

SyncHook

Executed when a module has been built successfully.

  • Callback Parameters: module

finishModules

AsyncSeriesHook

Called when all modules have been built without errors.

  • Callback Parameters: modules

finishRebuildingModule

SyncHook

Executed when a module has been rebuilt, in case of both success or with errors.

  • Callback Parameters: module

seal

SyncHook

Fired when the compilation stops accepting new modules.

unseal

SyncHook

Fired when a compilation begins accepting new modules.

optimizeDependenciesBasic

SyncBailHook

This hook will be removed in v5.0.0

Parameters: modules

optimizeDependencies

SyncBailHook

Fired at the beginning of dependency optimization.

  • Callback Parameters: modules

optimizeDependenciesAdvanced

SyncBailHook

This hook will be removed in v5.0.0

  • Callback Parameters: modules

afterOptimizeDependencies

SyncHook

Fired after the dependency optimization.

  • Callback Parameters: modules

optimize

SyncHook

Triggered at the beginning of the optimization phase.

optimizeModulesBasic

SyncBailHook

This hook will be removed in v5.0.0

  • Callback Parameters: modules

optimizeModules

SyncBailHook

Called at the beginning of the modules optimization phase. A plugin can tap into this hook to perform modules optimizations.

  • Callback Parameters: modules

optimizeModulesAdvanced

SyncBailHook

This hook will be removed in v5.0.0

  • Callback Parameters: modules

afterOptimizeModules

SyncHook

Called after modules optimization has completed.

  • Callback Parameters: modules

optimizeChunksBasic

SyncBailHook

This hook will be removed in v5.0.0

  • Callback Parameters: chunks

optimizeChunks

SyncBailHook

Called at the beginning of the chunks optimizion phase. A plugin can tap into this hook to perform chunks optimizations.

  • Callback Parameters: chunks

optimizeChunksAdvanced

SyncBailHook

This hook will be removed in v5.0.0

  • Callback Parameters: chunks

afterOptimizeChunks

SyncHook

Fired after chunk optimization has completed.

  • Callback Parameters: chunks

optimizeTree

AsyncSeriesHook

Called before optimizing the dependency tree. A plugin can tap into this hook to perform a dependency tree optimization.

  • Callback Parameters: chunks modules

afterOptimizeTree

SyncHook

Called after the dependency tree optimization has completed with success.

  • Callback Parameters: chunks modules

optimizeChunkModulesBasic

SyncBailHook

This hook will be removed in v5.0.0

  • Callback Parameters: chunks modules

optimizeChunkModules

SyncBailHook

Called after the tree optimization, at the beginning of the chunk modules optimization. A plugin can tap into this hook to perform optimizations of chunk modules.

  • Callback Parameters: chunks modules

optimizeChunkModulesAdvanced

SyncBailHook

This hook will be removed in v5.0.0

  • Callback Parameters: chunks modules

afterOptimizeChunkModules

SyncHook

Called after the chunkmodules optimization has successfully completed.

  • Callback Parameters: chunks modules

shouldRecord

SyncBailHook

Called to determine whether or not to store records. Returning anything !== false will prevent every other "record" hook from being executed (record, recordModules, recordChunks and recordHash).

reviveModules

SyncHook

Restore module information from records.

  • Callback Parameters: modules records

optimizeModuleOrder

SyncHook

This hook will be removed in v5.0.0

Sort the modules from most to least important.

  • Callback Parameters: modules

advancedOptimizeModuleOrder

SyncHook

This hook will be removed in v5.0.0

  • Callback Parameters: modules

beforeModuleIds

SyncHook

Executed before assigning an id to each module.

  • Callback Parameters: modules

moduleIds

SyncHook

Called to assign an id to each module.

  • Callback Parameters: modules

optimizeModuleIds

SyncHook

Called at the beginning of the modules id optimization.

  • Callback Parameters: modules

afterOptimizeModuleIds

SyncHook

Called when the modules id optimization phase has completed.

  • Callback Parameters: modules

reviveChunks

SyncHook

Restore chunk information from records.

  • Callback Parameters: chunks records

optimizeChunkOrder

SyncHook

This hook will be removed in v5.0.0

Sort the chunks in from most to least important.

  • Callback Parameters: chunks

beforeChunkIds

SyncHook

Executed before assigning an id to each chunk.

  • Callback Parameters: chunks

chunkIds

SyncHook

This hook will be available in v5.0.0

Called to assign an id to each chunk.

  • Callback Parameters: modules

beforeOptimizeChunkIds

SyncHook

This hook will be available in v5.0.0

Fired before chunks id optimization.

  • Callback Parameters: chunks

optimizeChunkIds

SyncHook

Called at the beginning of the chunks id optimization phase.

  • Callback Parameters: chunks

afterOptimizeChunkIds

SyncHook

Triggered after chunk id optimization has finished.

  • Callback Parameters: chunks

recordModules

SyncHook

Store module info to the records. This is only triggered if shouldRecord returns a truthy value.

  • Callback Parameters: modules records

recordChunks

SyncHook

Store chunk info to the records. This is only triggered if shouldRecord returns a truthy value.

  • Callback Parameters: chunks records

optimizeCodeGeneration

This hook will be available in v5.0.0

A plugin can tap into this hook to optimize the generated code.

  • Callback Parameters: modules

beforeModuleHash

This hook will be available in v5.0.0

Called before hashing modules.

afterModuleHash

This hook will be available in v5.0.0

Called after hashing modules.

beforeRuntimeRequirements

This hook will be available in v5.0.0

Called before processing the modules required at runtime.

  • Callback Parameters: entrypoints

afterRuntimeRequirements

This hook will be available in v5.0.0

Called after processing the runtime requirements.

beforeHash

SyncHook

Called before the compilation is hashed.

afterHash

SyncHook

Called after the compilation is hashed.

recordHash

SyncHook

Store information about record hash to the records. This is only triggered if shouldRecord returns a truthy value.

  • Callback Parameters: records

record

SyncHook

Store information about the compilation to the records. This is only triggered if shouldRecord returns a truthy value.

  • Callback Parameters: compilation records

beforeModuleAssets

SyncHook

Executed before module assets creation.

additionalChunkAssets

SyncHook

Create additional assets for the chunks.

  • Callback Parameters: chunks

shouldGenerateChunkAssets

SyncBailHook

Called to determine wheter or not generate chunks assets. Returning anything !== false will allow chunk assets generation.

beforeChunkAssets

SyncHook

Executed before creating the chunks assets.

additionalAssets

AsyncSeriesHook

Create additional assets for the compilation. This hook can be used to download an image, for example:

compilation.hooks.additionalAssets.tapAsync('MyPlugin', callback => {
  download('https://img.shields.io/npm/v/webpack.svg', function(resp) {
    if(resp.status === 200) {
      compilation.assets['webpack-version.svg'] = toAsset(resp);
      callback();
    } else {
      callback(new Error('[webpack-example-plugin] Unable to download the image'));
    }
  });
});

optimizeChunkAssets

AsyncSeriesHook

Optimize any chunk assets. The assets are stored in compilation.assets. A Chunk has a property files which points to all files created by a chunk. Any additional chunk assets are stored in compilation.additionalChunkAssets.

  • Callback Parameters: chunks

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

compilation.hooks
  .optimizeChunkAssets
  .tapAsync('MyPlugin', (chunks, callback) => {
    chunks.forEach(chunk => {
      chunk.files.forEach(file => {
        compilation.assets[file] = new ConcatSource(
          '\/**Sweet Banner**\/',
          '\n',
          compilation.assets[file]
        );
      });
    });

    callback();
  });

afterOptimizeChunkAssets

SyncHook

The chunk assets have been optimized.

  • Callback Parameters: chunks

Here's an example plugin from @boopathi that outputs exactly what went into each chunk.

compilation.hooks.afterOptimizeChunkAssets.tap('MyPlugin', chunks => {
  chunks.forEach(chunk => {
    console.log({
      id: chunk.id,
      name: chunk.name,
      includes: chunk.getModules().map(module => module.request)
    });
  });
});

optimizeAssets

AsyncSeriesHook

Optimize all assets stored in compilation.assets.

  • Callback Parameters: assets

afterOptimizeAssets

SyncHook

The assets have been optimized.

  • Callback Parameters: assets

needAdditionalSeal

SyncBailHook

Called to determine if the compilation needs to be unsealed to include other files.

afterSeal

AsyncSeriesHook

Executed right after needAdditionalSeal.

chunkHash

SyncHook

Triggered to emit the hash for each chunk.

  • Callback Parameters: chunk chunkHash

moduleAsset

SyncHook

Called when an asset from a module was added to the compilation.

  • Callback Parameters: module filename

chunkAsset

SyncHook

Triggered when an asset from a chunk was added to the compilation.

  • Callback Parameters: chunk filename

assetPath

SyncWaterfallHook

Called to determine the path of an asset.

  • Callback Parameters: path options

needAdditionalPass

SyncBailHook

Called to determine if a asset need to be processed further after being emitted.

childCompiler

SyncHook

Executed after setting up a child compiler.

  • Callback Parameters: childCompiler compilerName compilerIndex

normalModuleLoader

SyncHook

This hook will be moved in v5.0.0 to NormalModule.getCompilationHooks(compilation).loader

The normal module loader is the function that actually loads all the modules

in the module graph (one-by-one).

  • Callback Parameters: loaderContext module

dependencyReference

SyncWaterfallHook

This hooks allows changing the references reported by dependencies.

  • Callback Parameters: depRef dependency module

The module parameter will be removed in v5.0.0

Parser Hooks

The parser instance, found in the compiler, is used to parse each module being processed by webpack. The parser is yet another webpack class that extends tapable and provides a variety of tapable hooks that can be used by plugin authors to customize the parsing process.

The parser is found within module factories and therefore takes little more work to access:

compiler.hooks.normalModuleFactory.tap('MyPlugin', factory => {
  factory.hooks.parser.for('javascript/auto').tap('MyPlugin', (parser, options) => {
    parser.hooks.someHook.tap(/* ... */);
  });
});

As with the compiler, tapAsync and tapPromise may also be available depending on the type of hook.

Hooks

The following lifecycle hooks are exposed by the parser and can be accessed as such:

evaluateTypeof

SyncBailHook

Triggered when evaluating an expression consisting in a typeof of a free variable

  • Hook Parameters: identifier
  • Callback Parameters: expression
parser.hooks.evaluateTypeof.for('myIdentifier').tap('MyPlugin', expression => {
  /* ... */
  return expressionResult;
});

This will trigger the evaluateTypeof hook:

const a = typeof myIdentifier;

This won't trigger:

const myIdentifier = 0;
const b = typeof myIdentifier;

evaluate

SyncBailHook

Called when evaluating an expression.

  • Hook parameters: expressionType
  • Callback parameters: expression

For example:

index.js

const a = new String();

MyPlugin.js

parser.hooks.evaluate.for('NewExpression').tap('MyPlugin', expression => {
  /* ... */
  return expressionResult;
});

Where the expressions types are:

  • 'ArrowFunctionExpression'
  • 'AssignmentExpression'
  • 'AwaitExpression'
  • 'BinaryExpression'
  • 'CallExpression'
  • 'ClassExpression'
  • 'ConditionalExpression'
  • 'FunctionExpression'
  • 'Identifier'
  • 'LogicalExpression'
  • 'MemberExpression'
  • 'NewExpression'
  • 'ObjectExpression'
  • 'SequenceExpression'
  • 'SpreadElement'
  • 'TaggedTemplateExpression'
  • 'TemplateLiteral'
  • 'ThisExpression'
  • 'UnaryExpression'
  • 'UpdateExpression'

evaluateIdentifier

SyncBailHook

Called when evaluating an identifier that is a free variable.

  • Hook Parameters: identifier
  • Callback Parameters: expression

evaluateDefinedIdentifier

SyncBailHook

Called when evaluating an identifier that is a defined variable.

  • Hook Parameters: identifier
  • Callback Parameters: expression

evaluateCallExpressionMember

SyncBailHook

Called when evaluating a call to a member function of a successfully evaluated expression.

  • Hook Parameters: identifier
  • Callback Parameters: expression param

This expression will trigger the hook:

index.js

const a = expression.myFunc();

MyPlugin.js

parser.hooks.evaluateCallExpressionMember.for('myFunc').tap('MyPlugin', (expression, param) => {
  /* ... */
  return expressionResult;
});

statement

SyncBailHook

General purpose hook that is called for every parsed statement in a code fragment.

  • Callback Parameters: statement
parser.hooks.statement.tap('MyPlugin', statement => { /* ... */ });

Where the statement.type could be:

  • 'BlockStatement'
  • 'VariableDeclaration'
  • 'FunctionDeclaration'
  • 'ReturnStatement'
  • 'ClassDeclaration'
  • 'ExpressionStatement'
  • 'ImportDeclaration'
  • 'ExportAllDeclaration'
  • 'ExportDefaultDeclaration'
  • 'ExportNamedDeclaration'
  • 'IfStatement'
  • 'SwitchStatement'
  • 'ForInStatement'
  • 'ForOfStatement'
  • 'ForStatement'
  • 'WhileStatement'
  • 'DoWhileStatement'
  • 'ThrowStatement'
  • 'TryStatement'
  • 'LabeledStatement'
  • 'WithStatement'

statementIf

SyncBailHook

Called when parsing an if statement. Same as the statement hook, but triggered only when statement.type == 'IfStatement'.

  • Callback Parameters: statement

label

SyncBailHook

Called when parsing statements with a label. Those statements have statement.type === 'LabeledStatement'.

  • Hook Parameters: labelName
  • Callback Parameters: statement

import

SyncBailHook

Called for every import statement in a code fragment. The source parameter contains the name of the imported file.

  • Callback Parameters: statement source

The following import statement will trigger the hook once:

index.js

import _ from 'lodash';

MyPlugin.js

parser.hooks.import.tap('MyPlugin', (statement, source) => {
  // source == 'lodash'
});

importSpecifier

SyncBailHook

Called for every specifier of every import statement.

  • Callback Parameters: statement source exportName identifierName

The following import statement will trigger the hook twice:

index.js

import _, { has } from 'lodash';

MyPlugin.js

parser.hooks.importSpecifier.tap('MyPlugin', (statement, source, exportName, identifierName) => {
  /* First call
    source == 'lodash'
    exportName == 'default'
    identifierName == '_'
  */
  /* Second call
    source == 'lodash'
    exportName == 'has'
    identifierName == 'has'
  */
});

export

SyncBailHook

Called for every export statement in a code fragment.

  • Callback Parameters: statement

exportImport

SyncBailHook

Called for every export-import statement eg: export * from 'otherModule';.

  • Callback Parameters: statement source

exportDeclaration

SyncBailHook

Called for every export statement exporting a declaration.

  • Callback Parameters: statement declaration

Those exports will trigger this hook:

export const myVar = 'hello'; // also var, let
export function FunctionName(){}
export class ClassName {}

exportExpression

SyncBailHook

Called for every export statement exporting an expression e.g.export default expression;.

  • Callback Parameters: statement declaration

exportSpecifier

SyncBailHook

Called for every specifier of every export statement.

  • Callback Parameters: statement identifierName exportName index

exportImportSpecifier

SyncBailHook

Called for every specifier of every export-import statement.

  • Callback Parameters: statement source identifierName exportName index

varDeclaration

SyncBailHook

Called when parsing a variable declaration.

  • Callbak Parameters: declaration

varDeclarationLet

SyncBailHook

Called when parsing a variable declaration defined using let

  • Callbak Parameters: declaration

varDeclarationConst

SyncBailHook

Called when parsing a variable declaration defined using const

  • Callbak Parameters: declaration

varDeclarationVar

SyncBailHook

Called when parsing a variable declaration defined using var

  • Callbak Parameters: declaration

canRename

SyncBailHook

Triggered before renaming an identifier to determine if the renaming is allowed. This is usually used together with the rename hook.

  • Hook Parameters: identifier
  • Callback Parameters: expression
var a = b;

parser.hooks.canRename.for('b').tap('MyPlugin', expression => {
  // returning true allows renaming
  return true;
});

rename

SyncBailHook

Triggered when renaming to get the new identifier. This hook will be called only if canRename returns true.

  • Hook Parameters: identifier
  • Callback Parameters: expression
var a = b;

parser.hooks.rename.for('b').tap('MyPlugin', expression => {});

assigned

SyncBailHook

Called when parsing an AssignmentExpression before parsing the assigned expression.

  • Hook Parameters: identifier
  • Callback Parameters: expression
a += b;

parser.hooks.assigned.for('a').tap('MyPlugin', expression => {
  // this is called before parsing b
});

assign

SyncBailHook

Called when parsing an AssignmentExpression before parsing the assign expression.

  • Hook Parameters: identifier
  • Callback Parameters: expression
a += b;

parser.hooks.assigned.for('a').tap('MyPlugin', expression => {
  // this is called before parsing a
});

typeof

SyncBailHook

Triggered when parsing the typeof of an identifier

  • Hook Parameters: identifier
  • Callback Parameters: expression

call

SyncBailHook

Called when parsing a function call.

  • Hook Parameters: identifier
  • Callback Parameters: expression
eval(/* something */);

parser.hooks.call.for('eval').tap('MyPlugin', expression => {});

callAnyMember

SyncBailHook

Triggered when parsing a call to a member function of an object.

  • Hook Parameters: objectIdentifier
  • Callback Parameters: expression
myObj.anyFunc();

parser.hooks.callAnyMember.for('myObj').tap('MyPlugin', expression => {});

new

SyncBailHook

Invoked when parsing a new expression.

  • Hook Parameters: identifier
  • Callback Parameters: expression
new MyClass();

parser.hooks.new.for('MyClass').tap('MyPlugin', expression => {});

expression

SyncBailHook

Called when parsing an expression.

  • Hook Parameters: identifier
  • Callback Parameters: expression
const a = this;

parser.hooks.new.for('this').tap('MyPlugin', expression => {});

expressionAnyMember

SyncBailHook

Executed when parsing a MemberExpression.

  • Hook Parameters: identifier
  • Callback Parameters: expression
const a = process.env;

parser.hooks.new.for('process').tap('MyPlugin', expression => {});

expressionConditionalOperator

SyncBailHook

Called when parsing a ConditionalExpression e.g. condition ? a : b

  • Callback Parameters: expression

program

SyncBailHook

Get access to the abstract syntax tree (AST) of a code fragment

Parameters: ast comments

Plugin API

Plugins are a key piece of the webpack ecosystem and provide the community with a powerful way to tap into webpack's compilation process. A plugin is able to hook into key events that are fired throughout each compilation. Every step of the way, the plugin will have full access to the compiler and, when applicable, the current compilation.

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

Let's start by going over tapable utility, which provides the backbone of webpack's plugin interface.

Tapable

This small library is a core utility in webpack but can also be used elsewhere to provide a similar plugin interface. Many objects in webpack extend the Tapable class. The class exposes tap, tapAsync, and tapPromise methods which plugins can use to inject custom build steps that will be fired throughout a compilation.

Please see the documentation to learn more. An understanding of the three tap methods, as well as the hooks that provide them is crucial. The objects that extend Tapable (e.g. the compiler), the hooks they provide, and each hook's type (e.g. the SyncHook) will be noted.

Plugin Types

Depending on the hooks used and tap methods applied, plugins can function in a different number of ways. The way this works is closely related to the hooks provided by Tapable. The compiler hooks each note the underlying Tapable hook indicating which tap methods are available.

So depending on which event you tap into, the plugin may run differently. For example, when hooking into the compile stage, only the synchronous tap method can be used:

compiler.hooks.compile.tap('MyPlugin', params => {
  console.log('Synchronously tapping the compile hook.');
});

However, for run which utilizes the AsyncHook, we can utilize tapAsync or tapPromise (as well as tap):

compiler.hooks.run.tapAsync('MyPlugin', (source, target, routesList, callback) => {
  console.log('Asynchronously tapping the run hook.');
  callback();
});

compiler.hooks.run.tapPromise('MyPlugin', (source, target, routesList) => {
  return new Promise(resolve => setTimeout(resolve, 1000)).then(() => {
    console.log('Asynchronously tapping the run hook with a delay.');
  });
});

compiler.hooks.run.tapPromise('MyPlugin', async (source, target, routesList) => {
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log('Asynchronously tapping the run hook with a delay.');
});

The moral of the story is that there are a variety of ways to hook into the compiler, each one allowing your plugin to run as it sees fit.

Custom Hooks

In order to add a new hook to the compilation for other plugins to tap into, simply require the necessary hook class from tapable and create one:

const SyncHook = require('tapable').SyncHook;

// Within the `apply` method...
if (compiler.hooks.myCustomHook) throw new Error('Already in use');
compiler.hooks.myCustomHook = new SyncHook(['a', 'b', 'c']);

// Wherever/whenever you'd like to trigger the hook...
compiler.hooks.myCustomHook.call(a, b, c);

Again, see the documentation for tapable to learn more about the different hook classes and how they work.

Reporting Progress

Plugins can report progress via ProgressPlugin, which prints progress messages to stderr by default. In order to enable progress reporting, pass a --progress argument when running the webpack CLI.

It is possible to customize the printed output by passing different arguments to the reportProgress function of ProgressPlugin.

To report progress, a plugin must tap into a hook using the context: true option:

compiler.hooks.emit.tapAsync({
  name: 'MyPlugin',
  context: true
}, (context, compiler, callback) => {
  const reportProgress = context && context.reportProgress;
  if (reportProgress) reportProgress(0.95, 'Starting work');
  setTimeout(() => {
    if (reportProgress) reportProgress(0.95, 'Done work');
    callback();
  }, 1000);
});

The reportProgress function may be called with these arguments:

reportProgress(percentage, ...args);
  • percentage: This argument is unused; instead, ProgressPlugin will calculate a percentage based on the current hook.
  • ...args: Any number of strings, which will be passed to the ProgressPlugin handler to be reported to the user.

Note that only a subset of compiler and compilation hooks support the reportProgress function. See ProgressPlugin for a full list.

Logging

Logging API is available since the release of webpack 4.37. When logging is enabled in stats configuration and/or when infrastructure logging is enabled, plugins may log messages which will be printed out in the respective logger format (stats, infrastructure).

  • Plugins should prefer to use compilation.getLogger('PluginName') for logging. This kind of logging is stored to the Stats and formatted accordingly. It can be filtered and exported by the user.
  • Plugins may use the compiler.getInfrastructureLogger('PluginName') for logging. Using infrastructure logging is not stored in the Stats and therefore not formatted. It's usually logged to the console/dashboard/GUI directly. It can be filtered by the user.
  • Plugins may use special fallback logic for detecting logging support compilation.getLogger ? compilation.getLogger('PluginName') : console to provide a fallback for cases when an older webpack version is used which does not support getLogger method on compilation object.

Next Steps

See the compiler hooks section for a detailed listing of all the available compiler hooks and the parameters they make available.

Resolvers

Resolvers are created using the enhanced-resolve package. The Resolver class extends the tapable class and uses tapable to provide a few hooks. The enhanced-resolve package can be used directly to create new resolvers, however any compiler instance has a few resolver instances that can be tapped into.

Before reading on, make sure you at least skim through the enhanced-resolve and tapable documentation.

Types

There are three types of built-in resolvers available on the compiler class:

  • Normal: Resolves a module via an absolute or relative path.
  • Context: Resolves a module within a given context.
  • Loader: Resolves a webpack loader.

Depending on need, any one of these built-in resolver used by the compiler can be customized via plugins as such:

compiler.resolverFactory.plugin('resolver [type]', resolver => {
  resolver.hooks.resolve.tapAsync('MyPlugin', params => {
    // ...
  });
});

Where [type] is one of the three resolvers mention above, specified as:

  • normal
  • context
  • loader

See the enhanced-resolve documentation for a full list of hooks and descriptions.

Configuration Options

The resolvers mentioned above can also be customized via a configuration file with the resolve or resolveLoader options. These options allow users to change the resolving behavior through a variety of options including through resolve plugins.

The resolver plugins, e.g. DirectoryNamedPlugin, can be included directly in resolve.plugins rather than using standard plugins. Note that the resolve configuration affects the normal and context resolvers while resolveLoader is used to modify the loader resolver.

Compilation Object

Compilation object has many methods and hooks avaialble. On this page we will list the available methods and properties.

compilation object methods

getStats

function

Returns Stats object for the current compilation.

addModule

function (module, cacheGroup)

Adds a module to the current compilation.

Parameters:

  • module - module to be added
  • cacheGroup - cacheGroup of the module

getModule

function (module)

Fetches a module from a compilation by its identifier.

Parameters:

  • module - module to be fetched. Identifier is extracted from the module by the compilation using module.identifier() method.

findModule

function (module)

Attempts to search for a module by its identifier.

Parameters:

  • module - module to be searched for. Identifier is extracted from the module by the compilation using module.identifier() method.

waitForBuildingFinished

function (module, callback)

Runs a given callback function when given module was built.

Parameters:

  • module - module at question.
  • callback - a function to be invoked.

buildModule

function (module, optional, origin, dependencies)

Builds the given module.

Parameters:

  • module - the module to be built.
  • optional - optional flag.
  • origin - origin module from which this module build was requested.
  • dependencies - optional dependencies of the module to be built.

processModuleDependencies

function (module, callback)

Process the given module dependencies.

Parameters:

  • module - module to be processed for the dependencies.
  • callback - function to be invoked when dependencies of the module had been processed.

addModuleDependencies

function (module, dependencies, bail, cacheGroup, recursive, callback)

Adds dependencies to the module. Automatically called by processModuleDependencies after processing dependencies.

Parameters:

  • module - module to add dependencies to.
  • dependencies - set of sorted dependencies to iterate through and add to the module.
  • bail - whether to bail or not when error occurs.
  • cacheGroup - cacheGroup of the module.
  • recursive - whether it is a recursive traversal.
  • callback - function to invoke after adding the module dependencies.

addEntry

function (context, entry, name, callback)

Adds an entry to the compilation.

Parameters:

  • context - context path for entry.
  • entry - entry dependency.
  • name - name of entry.
  • callback - function to be invoked when addEntry finishes.

prefetch

function (context, dependency, callback)

Creates a module from given dependency.

Parameters:

  • context - context path.
  • dependency - dependency that was used to create the module.
  • callback - module callback that sends a module up one level.

rebuildModule

function (module, thisCallback)

Triggers a re-build of the module.

Parameters:

  • module - module to be rebuilt.
  • thisCallback - function to be invoked when the module finishes rebuilding.

finish

function (callback)

Finishes compilation and invokes given callback.

Parameters:

  • callback - function to be invoked when the compilation has been finished.

seal

function (callback)

Seals the compilation.

Parameters:

  • callback - function to be invoked when the compilation has been sealed.

unseal

function

Unseals the compilation.

Parameters:

  • callback - function to be invoked when compilation has been sealed.

reportDependencyErrorsAndWarnings

function (module, blocks)

Adds errors and warnings of the given module to the compilation errors and warnings.

Parameters:

  • module - the module which's errors and warnings to be reported.
  • blocks - a set of dependencies blocks to report from.

addChunkInGroup

function (groupOptions, module, loc, request)

Adds module to an existing chunk group or creates a new one. Returns a chunkGroup.

Parameters:

  • groupOptions - options for the chunk group.
  • module - a module that references the chunk group.
  • loc - the location from which the chunk group is referenced (inside of the module).
  • request - the request from which the chunk group is referenced.

addChunk

function (name)

Creates and adds a new chunk to the compilation.chunks. Returns that chunk.

Parameters:

  • name - the name of the chunk.

assignDepth

function (module)

Assigns depth to the given module and its depencency blocks recursively.

Parameters:

  • module - the module to assign depth to.

getDependencyReference

function (module, dependency)

Returns the reference to the dependency from a given module.

Parameters:

  • module - the module at question.
  • dependency - the dependency to get reference to.

processDependenciesBlocksForChunkGroups

function (inputChunkGroups)

Creates the Chunk graph from the Module graph. The process is done in two phases. Phase one: traverse the module graph and build a basic chunks graph in chunkDependencies. Phase two: traverse every possible way through the basic chunk graph and track the available modules. While traversing, processDependenciesBlocksForChunkGroups connects chunks with each other and Blocks with Chunks. It stops traversing when all modules for a chunk are already available and it doesn't connect unneeded chunks.

Parameters:

  • inputChunkGroups - chunk groups which are processed.

removeReasonsOfDependencyBlock

function (module, block)

Removes relation of the module to dependency block.

Parameters:

  • module - a module relationship to be removed.
  • block - dependency block.

patchChunksAfterReasonRemoval

function (module, chunk)

Patches ties of module and chunk after removing dependecy reasons. Called automatically by removeReasonsOfDependencyBlock.

Parameters:

  • module - a module to patch tie.
  • chunk - a chunk to patch tie.

removeChunkFromDependencies

function (block, chunk)

Removes given chunk from a dependecies block module and chunks after removing dependecy reasons. Called automatically by removeReasonsOfDependencyBlock.

Parameters:

  • block - block tie for Chunk.
  • chunk - a chunk to remove from dependencies.

applyModuleIds

function

applyChunkIds

function

sortItemsWithModuleIds

function

sortItemsWithChunkIds

function

summarizeDependencies

function

createHash

function

modifyHash

function (update)

createModuleAssets

function

createChunkAssets

function

getPath

function (filename, data)

Parameters:

  • filename - used to get asset path with hash.
  • data - data object.

createChildCompiler

function (name, outputOptions, plugins)

Allows to run another instance of webpack inside of webpack. However as a child with different settings and configurations applied. It copies all hooks and plugins from parent (or top level compiler) and creates a child Compiler instance. Returns the created Compiler.

Parameters:

  • name - name for the child Compiler.
  • outputOptions - output options object.
  • plugins - webpack plugins that will be applied.

checkConstraints

function

emitAsset

function (file, source, assetInfo = {})

Available since webpack 4.40.0

Parameters:

  • file - file name of the asset
  • source - source of the asset
  • assetInfo - additional asset information

updateAsset

function (file, newSourceOrFunction, assetInfoUpdateOrFunction)

Available since webpack 4.40.0

Parameters:

  • file - file name of the asset
  • newSourceOrFunction - new asset source or function converting old to new
  • assetInfoUpdateOrFunction - new asset info or function converting old to new

getAssets

function

Available since webpack 4.40.0

Returns array of all assets under current compilation.

getAsset

function (name)

Available since webpack 4.40.0

Parameters:

name - the name of the asset to return


Contributors