## 1. Project Overview & Quickstart (webpack/webpack-dev-server)

## File: README.md

[![npm][npm]][npm-url]
[![node][node]][node-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![discussion][discussion]][discussion-url]
[![downloads][downloads]][npm-url]
[![contributors][contributors]][contributors-url]

# webpack-dev-server

Use [webpack](https://webpack.js.org) with a development server that provides
live reloading. This should be used for **development only**.

It uses [webpack-dev-middleware][middleware-url] under the hood, which provides
fast in-memory access to the webpack assets.

## Table of Contents

- [Getting Started](#getting-started)
- [Usage](#usage)
  - [With the CLI](#with-the-cli)
  - [With NPM Scripts](#with-npm-scripts)
  - [With the API](#with-the-api)
  - [With TypeScript](#with-typescript)
  - [The Result](#the-result)
- [Browser Support](#browser-support)
- [Support](#support)
- [Contributing](#contributing)
- [Attribution](#attribution)
- [License](#license)

## Getting Started

First things first, install the module:

```console
npm install webpack-dev-server --save-dev
```

or

```console
yarn add -D webpack-dev-server
```

or

```console
pnpm add -D webpack-dev-server
```

_Note: While you can install and run webpack-dev-server globally, we recommend
installing it locally. webpack-dev-server will always use a local installation
over a global one._

## Usage

There are two main, recommended methods of using the module:

### With the CLI

The easiest way to use it is with the [webpack CLI](https://webpack.js.org/api/cli/). In the directory where your
`webpack.config.js` is, run:

```console
npx webpack serve
```

Following options are available with `webpack serve`:

```
/* Detailed source-code truncated for AI context efficiency. */
```

> [!NOTE]
>
> _Detailed documentation for above options is available on this [link](https://webpack.js.org/configuration/dev-server/)._

### With NPM Scripts

NPM package.json scripts are a convenient and useful means to run locally installed
binaries without having to be concerned about their full paths. Simply define a
script as such:

```json
{
  "scripts": {
    "serve": "webpack serve"
  }
}
```

And run the following in your terminal/console:

```console
npm run serve
```

NPM will automatically refer to the the binary in `node_modules` for you, and
execute the file or command.

### With the API

While it's recommended to run webpack-dev-server via the CLI, you may also choose to start a server via the API.

See the related [API documentation for `webpack-dev-server`](https://webpack.js.org/api/webpack-dev-server/).

### With TypeScript

If you use TypeScript in the webpack config, you'll need to properly type `devServer` property in order to avoid TS errors (e.g. `'devServer' does not exist in type 'Configuration'`). For that use either:

```ts
/// <reference path="node_modules/webpack-dev-server/types/lib/Server.d.ts"/>
import { type Configuration } from "webpack";

// Your logic
```

Or you can import the type from `webpack-dev-server`, i.e.

```ts
import { type Configuration } from "webpack";
import { type Configuration as DevServerConfiguration } from "webpack-dev-server";

const devServer: DevServerConfiguration = {};
const config: Configuration = { devServer };

// module.exports
export default config;
```

### The Result

Either method will start a server instance and begin listening for connections
from `localhost` on port `8080`.

webpack-dev-server is configured by default to support live-reload of files as
you edit your assets while the server is running.

See [**the documentation**][docs-url] for more use cases and options.

## Browser Support

While `webpack-dev-server` transpiles the client (browser) scripts to an ES5
state, the project only officially supports the _last two versions of major
browsers_. We simply don't have the resources to support every whacky
browser out there.

If you find a bug with an obscure / old browser, we would actively welcome a
Pull Request to resolve the bug.

## Support

We do our best to keep issues in the repository focused on bugs, features, and
needed modifications to the code for the module. Because of that, we ask users
with general support, "how-to", or "why isn't this working" questions to try one
of the other support channels that are available.

Your first-stop-shop for support for webpack-dev-server should be the excellent
[documentation][docs-url] for the module. If you see an opportunity for improvement
of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a
pull request.

From there, we encourage users to visit the [webpack discussions][discussion-url] and
talk to the fine folks there. If your quest for answers comes up dry in chat,
head over to [StackOverflow][stack-url] and do a quick search or open a new
question. Remember; It's always much easier to answer questions that include your
`webpack.config.js` and relevant files!

If you're twitter-savvy you can tweet [#webpack][hash-url] with your question
and someone should be able to reach out and lend a hand.

If you have discovered a :bug:, have a feature suggestion, or would like to see
a modification, please feel free to create an issue on Github. _Note: The issue
template isn't optional, so please be sure not to remove it, and please fill it
out completely._

## Contributing

We welcome your contributions! Please have a read of [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how to get involved.

## Attribution

This project is heavily inspired by [peerigon/nof5](https://github.com/peerigon/nof5).

## License

#### [MIT](./LICENSE)

[npm]: https://img.shields.io/npm/v/webpack-dev-server.svg
[npm-url]: https://npmjs.com/package/webpack-dev-server
[node]: https://img.shields.io/node/v/webpack-dev-server.svg
[node-url]: https://nodejs.org
[tests]: https://github.com/webpack/webpack-dev-server/workflows/webpack-dev-server/badge.svg
[tests-url]: https://github.com/webpack/webpack-dev-server/actions?query=workflow%3Awebpack-dev-server
[cover]: https://codecov.io/gh/webpack/webpack-dev-server/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack/webpack-dev-server
[discussion]: https://img.shields.io/github/discussions/webpack/webpack
[discussion-url]: https://github.com/webpack/webpack/discussions
[docs-url]: https://webpack.js.org/configuration/dev-server/#devserver
[hash-url]: https://twitter.com/search?q=webpack
[middleware-url]: https://github.com/webpack/webpack-dev-middleware
[stack-url]: https://stackoverflow.com/questions/tagged/webpack-dev-server
[uglify-url]: https://github.com/webpack-contrib/uglifyjs-webpack-plugin
[wjo-url]: https://github.com/webpack/webpack.js.org
[downloads]: https://img.shields.io/npm/dm/webpack-dev-server.svg
[contributors-url]: https://github.com/webpack/webpack-dev-server/graphs/contributors
[contributors]: https://img.shields.io/github/contributors/webpack/webpack-dev-server.svg

---

## File: examples/proxy/README.md

# proxy

Proxying some URLs can be useful when you have a separate API backend development server and you want to send API requests on the same domain.

**webpack.config.js**

```js
module.exports = {
  // ...
  devServer: {
    proxy: {
      "/proxy": {
        target: "http://localhost:5000",
      },
    },
  },
};
```

To run this example use the following command:

```console
npx webpack serve --open
```

## What Should Happen

1. The script start a proxy server on `http://localhost:5000/` and open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success! Now visit /proxy`.
3. Now visit the `/proxy` route by clicking on the `/proxy` text, you should see the text on the page itself change to read `response from proxy`.

---

## File: examples/open-target-multiple/README.md

# Open Target Option (Multiple)

**webpack.config.js**

```js
module.exports = {
  // ...
  devServer: {
    open: {
      target: ["/example1.html", "example2.html"],
    },
  },
};
```

Usage via CLI:

```console
npx webpack serve --open-target example1.html --open-target example2.html
```

Some applications may consist of multiple pages. During development it may
be useful to directly open multiple pages at the same time. The pages to open
may be specified as the argument to the `open-target` option.

## What Should Happen

The script should open `http://localhost:8080/example1.html` and
`http://localhost:8080/example2.html` in your default browser.
You should see the text on the page itself change to read `Success!`.

---

## File: examples/open-target/README.md

# Open Target Option

## Open default generated URL in browser:

**webpack.config.js**

```js
module.exports = {
  // ...
  devServer: {
    open: {
      target: "",
    },
  },
};
```

Usage via CLI:

```
npx webpack serve --open-target 
```

## Open specific page in browser:

**webpack.config.js**

```js
module.exports = {
  // ...
  devServer: {
    open: {
      target: "/example.html#page1",
    },
  },
};
```

Usage via CLI:

```
npx webpack serve --open-target /example.html#page1
```

## Open specific browser:

**webpack.config.js**

```js
module.exports = {
  // ...
  devServer: {
    open: {
      app: "firefox",
    },
  },
};
```

Usage via CLI:

```
npx webpack serve --open-app-name firefox
```

## Open specific page in specific browser:

**webpack.config.js**

```js
module.exports = {
  // ...
  devServer: {
    open: {
      target: "/example.html#page1",
      app: "firefox",
    },
  },
};
```

Usage via CLI:

```
npx webpack serve --open-target example.html#page1 --open-app-name firefox
```

Some applications may consist of multiple pages. During development it may
be useful to directly open a particular page. The page to open may be specified
as the argument to the `open-target` option.

## What Should Happen

The script should open `http://localhost:8080/example.html#page1` in your
default/specified browser. You should see the text on the page itself change to read `Success!`.

---

## File: examples/on-listening/README.md

# onListening

Provides the ability to execute a custom function when webpack-dev-server starts listening for connections on a port.

**webpack.config.js**

```js
module.exports = {
  // ...
  devServer: {
    onListening: (devServer) => {
      const { port } = devServer.server.address();
      console.log("Listening on port:", port);
    },
  },
};
```

To run this example use the following command:

```console
npx webpack serve --open
```

## What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. Check the terminal output, you should see `Listening on port: 8080` in the output.

---

## File: examples/node-false/README.md

# Webpack `node` Option

```console
npx webpack serve --open
```

## What should happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.

---

## File: examples/multi-compiler/README.md

# Multi Compiler

`webpack-dev-server` should be able to compile multiple webpack configs.

```shell
npx webpack serve --open
```

## What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. In `app.js` write code containing a syntax error and save the file.
4. The page should now refresh and show a full screen error overlay, displaying
   the syntax error.

---

## File: examples/ipc/README.md

# IPC

The Unix socket to listen to (instead of a [host](../host-and-port/README.md)).

## true

Setting it to `true` will listen to a socket at `/your-os-temp-dir/webpack-dev-server.sock`:

**webpack.config.js**

```js
module.exports = {
  // ...
  devServer: {
    ipc: true,
  },
};
```

Usage via CLI:

```console
npx webpack serve --ipc
```

## string

You can also listen to a different socket with:

**webpack.config.js**

```js
const path = require("node:path");

module.exports = {
  // ...
  devServer: {
    ipc: path.join(__dirname, "my-socket.sock"),
  },
};
```

Usage via CLI:

```console
npx webpack serve --ipc ./my-socket.sock
```

## What Should Happen

1. The script should listen to the socket provided.
1. A proxy server should be created.
1. Go to `http://localhost:8080/`, you should see the text on the page itself change to read `Success!`.

---

## File: examples/host-and-port/README.md

# Host and Port Options

You may choose to wish to change the host and port on which `webpack-dev-server`
will run. The `host` and `port` options allow for that.

## host

### IPv4

**webpack.config.js**

```js
module.exports = {
  // ...
  devServer: {
    host: "0.0.0.0",
    port: 5000,
  },
};
```

Usage via CLI:

```console
npx webpack serve --open --port 5000 --host 0.0.0.0
```

### IPv6

_This also works with IPv6_

**webpack.config.js**

```js
module.exports = {
  // ...
  devServer: {
    host: "::",
    port: 5000,
  },
};
```

Usage via CLI:

```console
npx webpack serve --open --port 5000 --host ::
```

### local-ip

Specifying `local-ip` as `host` will try to resolve the `host` option as your local `IPv4` address if available, if `IPv4` is not available it will try to resolve your local `IPv6` address.

```js
module.exports = {
  // ...
  devServer: {
    host: "local-ip",
    port: 5000,
  },
};
```

Usage via CLI:

```console
npx webpack serve --open --port 5000 --host local-ip
```

### local-ipv4

Specifying `local-ipv4` as `host` will try to resolve the `host` option as your local `IPv4` address.

```js
module.exports = {
  // ...
  devServer: {
    host: "local-ipv4",
    port: 5000,
  },
};
```

Usage via CLI:

```console
npx webpack serve --open --port 5000 --host local-ipv4
```

### local-ipv6

Specifying `local-ipv6` as `host` will try to resolve the `host` option as your local `IPv6` address.

```js
module.exports = {
  // ...
  devServer: {
    host: "local-ipv6",
    port: 5000,
  },
};
```

Usage via CLI:

```console
npx webpack serve --open --port 5000 --host local-ipv6
```

#### What Should Happen

1. The script should open `http://0.0.0.0:5000/` if specifying the IPv4 option,
   or `http://[::]:5000/` for IPv6, in your default browser.
2. You should see the text on the page itself change to read `Success!`.

## port

### specific port

Tell the server to connect to a specific port with the following:

```js
module.exports = {
  // ...
  devServer: {
    port: 9000,
  },
};
```

Usage via CLI:

```console
npx webpack serve --open --port 9000
```

#### What Should Happen

1. The script should open `http://localhost:9000/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.

### auto

Specifying `auto` as `port` will try to connect the server to the default port `8080` and if not available it will automatically search for another free port.

```js
module.exports = {
  // ...
  devServer: {
    port: "auto",
  },
};
```

Usage via CLI:

```console
npx webpack serve --open --port auto
```

#### What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. You should see the text on the page itself change to read `Success!`.
3. Keep the server open and switch to a new terminal window.
4. Run the script once again.
5. The script should open `http://localhost:8081/` (or any other port if it is not free) in your default browser.

---

## File: examples/hmr/only/README.md

# Hot Module Reloading

Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running, without a full reload of the page.

## only

Enables Hot Module Replacement without page refresh as a fallback in case of build failures.

**webpack.config.js**

```js
module.exports = {
  // ...
  devServer: {
    hot: "only",
  },
};
```

Usage via CLI:

```console
npx webpack serve --open --hot only
```

## What Should Happen

1. The script should open `http://localhost:8080/` in your default browser.
2. In your editor, open `example.js` and change any part of the `innerHTML` string.
3. Open the console in your browser's devtools.

In the devtools console you should see:

```
[webpack-dev-server] App updated. Recompiling...
[webpack-dev-server] App hot update...
[HMR] Checking for updates on the server...
 ⚠️ Ignored an update to unaccepted module ./example.js -> ./app.js
[HMR] Nothing hot Updated.
[HMR] App is up to date.
```

5. Refresh the page and see the text on the page itself change to match your edits in `example.js`.

## 2. Official Technical Reference & Guides (webpack/webpack.js.org)

## File: README.md

## Content Progress

Now that we've covered much of the backlog of _missing documentation_, we are
starting to heavily review each section of the site's content to sort and
structure it appropriately. The following issues should provide a pretty good
idea of where things are, and where they are going:

- [Guides - Review and Simplify][guides-url]
- [Concepts - Review and Organize][concepts-url]

We haven't created issues for the other sections yet, but they will be coming
soon. For dev-related work please see [General - Updates & Fixes][general-url].

## Translation

To help translate this documentation please jump to the [translation branch][translate-url].

## Versioning

Since webpack 4 we have created a subdomain-based archive for older states of documentation
matching older webpack version. Webpack 4's documentation is available at
[https://v4.webpack.js.org/](https://v4.webpack.js.org/) and is deployed from [`gh-pages` branch of v4.webpack.js.org repository](https://github.com/webpack/v4.webpack.js.org/tree/gh-pages)

There are various known issues that need fixing ([#3366](https://github.com/webpack/webpack.js.org/issues/3366)).

## Contributing

Read through the [writer's guide][writer-guide-url] if you're interested in editing the
content on this site. See the [contributors page][contributing-url] to learn how to set up and
start working on the site locally.

## License

The content is available under the [Creative Commons BY 4.0][license-url] license.

## Special Thanks

If you want to reach us at webpack, contact us and we can arrange something in return for your donations!

_Vercel_ has given us a Pro account.

[![VercelLogo][vercel]][vercel-url]

[build-status]: https://github.com/webpack/webpack.js.org/workflows/Deploy/badge.svg
[build-status-url]: https://github.com/webpack/webpack.js.org/actions
[vercel]: ./src/assets/powered-by-vercel.svg
[vercel-url]: https://vercel.com/?utm_source=webpackdocs
[discussion]: https://img.shields.io/github/discussions/webpack/webpack
[discussion-url]: https://github.com/webpack/webpack/discussions
[concepts-url]: https://github.com/webpack/webpack.js.org/issues/1386
[contributing-url]: https://github.com/webpack/webpack.js.org/blob/main/.github/CONTRIBUTING.md
[general-url]: https://github.com/webpack/webpack.js.org/issues/1525
[guides-url]: https://github.com/webpack/webpack.js.org/issues/1258
[license-url]: https://creativecommons.org/licenses/by/4.0/
[release]: https://img.shields.io/badge/release-standard%20version-brightgreen.svg
[release-url]: https://github.com/conventional-changelog/standard-version
[translate-url]: https://github.com/webpack/webpack.js.org/tree/translation
[writer-guide-url]: https://webpack.js.org/contribute/writers-guide

---

## File: examples/module-federation/README.md

# Module Federation

## How to use

Run the following commands in the root directory.

```bash
npm install
npm start
```

Both `app1` and `app2` are independently deployed apps:

- `app1`: http://localhost:3001
- `app2`: http://localhost:3002

Check out this link below for more examples:

[https://github.com/module-federation/module-federation-examples](https://github.com/module-federation/module-federation-examples)

---

## File: examples/getting-started/README.md

# Getting Started

## How to use

Run the following commands in the root directory.

```bash
npm install
npm run build
npm run start
```

---

## File: repositories/README.md

# webpack documentation repositories

The files in this directory are auto generated from [`fetch-package-repos.mjs`](../src/utilities/fetch-package-repos.mjs) and should not be edited by hand. Any manual changes will be overwritten by the automation next time it runs.

---

## File: src/content/api/cli.mdx

---
title: Command Line Interface
sort: 1
contributors:
  - anshumanv
  - rishabh3112
  - snitin315
  - evenstensberg
  - simon04
  - tbroadley
  - chenxsan
  - rencire
  - madhavarshney
  - EugeneHlushko
  - byzyk
  - wizardofhogwarts
  - EslamHiko
  - smelukov
  - anikethsaha
  - jamesgeorge007
  - burhanuday
related:
  - title: Analyzing Build Statistics
    url: https://survivejs.com/webpack/optimizing-build/analyzing-build-statistics/
  - title: Three simple ways to inspect a webpack bundle
    url: https://medium.com/@joeclever/three-simple-ways-to-inspect-a-webpack-bundle-7f6a8fe7195d#.7d2i06mjx
  - title: Optimising your application bundle size with webpack
    url: https://hackernoon.com/optimising-your-application-bundle-size-with-webpack-e85b00bab579#.5w5ko08pq
  - title: Analysing and minimising the size of client-side bundle with webpack and source-map-explorer
    url: https://medium.com/@nimgrg/analysing-and-minimising-the-size-of-client-side-bundle-with-webpack-and-source-map-explorer-41096559beca#.c3t2srr8x
---

For proper usage and easier 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 configuration file.

Read the [installation guide](/guides/installation) if you don't already have webpack and CLI installed.

W> `webpack-cli` v7.0.0+ requires node >= v20.9.0, `webpack >= v5.101.0`, and `webpack-dev-server >= v5.0.0`.

W> If you want to run webpack using `npx` please make sure you have `webpack-cli` installed.

## Commands

webpack-cli offers a variety of commands to make working with webpack easier. By default webpack ships with

| Command                     | Usage                                     | Description                                                                                        |
| --------------------------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------- |
| [`build`](#build)           | `build\|bundle\|b [entries...] [options]` | Run webpack (default command, can be omitted).                                                     |
| [`configtest`](#configtest) | `configtest\|t [config-path]`             | Validate a webpack configuration.                                                                  |
| [`help`](#help)             | `help\|h [command] [option]`              | Display help for commands and options.                                                             |
| [`info`](#info)             | `info\|i [options]`                       | Outputs information about your system.                                                             |
| [`serve`](#serve)           | `serve\|server\|s [options]`              | Run the `webpack-dev-server`.                                                                      |
| [`version`](#version)       | `version\|v [commands...]`                | Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and other packages. |
| [`watch`](#watch)           | `watch\|w [entries...] [options]`         | Run webpack and watch for files changes.                                                           |

### Build

Run webpack (default command, can be omitted).

```bash
npx webpack build [options]
```

**example**

```bash
npx webpack build --config ./webpack.config.js --stats verbose
```

### Init

Used to initialize a new webpack project using `create-webpack-app`.

```bash
npx create-webpack-app [generation-path] [options]
```

**example**

```bash
npx create-webpack-app ./my-app --force --template=default
```

Alias to:

```bash
npx create-webpack-app init ./my-app --force --template=default
```

#### Generation Path

Location of where to generate the configuration. Defaults to `process.cwd()`.

#### Options

**`-t`, `--template`**

`string = 'default'`

Name of template to generate.

**`-f`, `--force`**

`boolean`

To generate a project without questions. When enabled, the default answer for each question will be used.

#### Templates supported

- `--template=default` - Default template with basic configuration.
- `--template=react` - Template with React configuration.
- `--template=vue` - Template with Vue configuration.
- `--template=svelte` - Template with Svelte configuration.`

### Loader

Scaffold a loader.

```bash
npx create-webpack-app loader [output-path] [options]
```

**example**

```bash
npx create-webpack-app loader ./my-loader --template=default
```

#### Output Path

Path to the output directory, e.g. `./loader-name`.

#### Options

**`-t`, `--template`**

`string = 'default'`

Type of template.

### Plugin

Scaffold a plugin.

```bash
npx create-webpack-app plugin [output-path] [options]
```

**example**

```bash
npx create-webpack-app plugin ./my-plugin --template=default
```

#### Output Path

Path to the output directory, e.g. `./plugin-name`.

#### Options

**`-t`, `--template`**

`string = 'default'`

Type of template.

T> See the [full documentation of `create-webpack-app`](https://github.com/webpack/webpack-cli/blob/master/packages/create-webpack-app/README.md).

### Info

Outputs information about your system.

```bash
npx webpack info [options]
```

**example**

```bash
npx webpack info --output json --addition-package postcss
```

#### Options for info

**`-a`, `--additional-package`**

`string`

Adds additional packages to the output.

**example**

```bash
npx webpack info --additional-package postcss
```

**`-o`, `--output`**

`string : 'json' | 'markdown'`

To get the output in a specified format.

**example**

```bash
npx webpack info --output markdown
```

### Configtest

Validate a webpack configuration.

```bash
npx webpack configtest [config-path]
```

**example**

```bash
npx webpack configtest ./webpack.config.js
```

#### Config Path

Path to your webpack configuration file. Defaults to `./webpack.config.js`.

### Serve

Run the webpack dev server.

```bash
npx webpack serve [options]
```

**example**

```bash
npx webpack serve --static --open
```

T> See the [full list of options for `webpack serve` command](https://github.com/webpack/webpack-cli/blob/master/SERVE-OPTIONS-v4.md) and [related documentation for webpack-dev-server](/configuration/dev-server).

### Watch

Run webpack and watch for files changes.

```bash
npx webpack watch [options]
```

**example**

```bash
npx webpack watch --mode development
```

## Flags

By default webpack ships with the following flags:

| Flag / Alias                            | Type            | Description                                                               |
| --------------------------------------- | --------------- | ------------------------------------------------------------------------- |
| [`--entry`](#entry)                     | string[]        | The entry point(s) of your application e.g. `./src/main.js`               |
| [`--config, -c`](#config)               | string[]        | Provide path to a webpack configuration file e.g. `./webpack.config.js`   |
| [`--config-name`](#config-name)         | string[]        | Name of the configuration to use                                          |
| `--name`                                | string          | Name of the configuration. Used when loading multiple configurations      |
| `--color`                               | boolean         | Enable colors on console                                                  |
| [`--merge, -m`](#merge)                 | boolean         | Merge two or more configurations using `webpack-merge`                    |
| [`--env`](#env)                         | string[]        | Environment passed to the configuration when it is a function             |
| [`--config-node-env`](#config-node-env) | string          | Set `process.env.NODE_ENV` to the specified value                         |
| [`--progress`](#progress)               | boolean, string | Print compilation progress during build                                   |
| [`--help`](#help)                       | boolean         | Outputs list of supported flags and commands                              |
| [`--output-path, -o`](#output-path)     | string          | Output location of the file generated by webpack e.g. `./dist`            |
| `--target, -t`                          | string[]        | Sets the build target                                                     |
| `--watch, -w`                           | boolean         | Watch for file changes                                                    |
| `--watch-options-stdin`                 | boolean         | Stop watching when stdin stream has ended                                 |
| `--devtool, -d`                         | string          | Controls if and how source maps are generated.                            |
| [`--json, -j`](#json)                   | boolean, string | Prints result as JSON or store it in a file                               |
| `--mode`                                | string          | Defines the mode to pass to webpack                                       |
| [`--version, -v`](#version)             | boolean         | Get current version                                                       |
| `--stats`                               | boolean, string | It instructs webpack on how to treat the stats                            |
| `--disable-interpret`                   | boolean         | Disable interpret for loading the config file.                            |
| `--fail-on-warnings`                    | boolean         | Stop webpack-cli process with non-zero exit code on warnings from webpack |
| [`--analyze`](#analyzing-bundle)        | boolean         | It invokes `webpack-bundle-analyzer` plugin to get bundle information     |
| [`--extends, -e`](#extends)             | string[]        | Extend an existing configuration                                          |

### Negated Flags

| Flag                       | Description                                                   |
| -------------------------- | ------------------------------------------------------------- |
| `--no-color`               | Disables any color on the console                             |
| `--no-hot`                 | Disables hot reloading if you have it enabled via your config |
| `--no-stats`               | Disables any compilation stats emitted by webpack             |
| `--no-watch`               | Do not watch for file changes                                 |
| `--no-devtool`             | Do not generate source maps                                   |
| `--no-watch-options-stdin` | Do not stop watching when stdin stream has ended              |

### Core Flags

Starting CLI v4 and webpack v5, CLI imports the entire configuration schema from webpack core to allow tuning almost every configuration option from the command line.

**Here's the list of all the core flags supported by webpack v5 with CLI v4 - [link](https://github.com/webpack/webpack-cli/blob/master/OPTIONS.md)**

For example if you want to enable performance hints in your project you'd use [this](https://webpack.js.org/configuration/performance/#performancehints) option in configuration, with core flags you can do -

```bash
npx webpack --performance-hints warning
```

## Usage

### With configuration file

```bash
npx webpack [--config webpack.config.js]
```

See [configuration](/configuration) for the options in the configuration file.

### Without configuration file

```bash
npx webpack --entry <entry> --output-path <output-path>
```

**example**

```bash
npx webpack --entry ./first.js --entry ./second.js --output-path /build
```

#### 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).
Following are the multiple ways of specifying entry file(s) via CLI -

```bash
npx webpack --entry-reset ./first-entry.js
```

```bash
npx webpack --entry-reset --entry ./first-entry.js
```

```bash
npx webpack --entry-reset ./first-entry.js ./other-entry.js
```

```bash
npx webpack --entry-reset --entry ./first-entry.js ./other-entry.js
```

W> The `--entry-reset` option is required to replace the existing [entry](/configuration/entry-context/#entry) option, without it the `--entry` option will add another entry to the existing entries.

T> Use `webpack [command] --entry-reset [entries...] [option]` syntax because some options can accept multiple values so `webpack --target node ./entry.js` means `target: ['node', './entry.js']`

#### output-path

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

**Example**

If your project structure is as follows -

```bash
.
├── dist
├── index.html
└── src
    ├── index.js
    ├── index2.js
    └── others.js
```

```bash
npx webpack ./src/index.js --output-path dist
```

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

```bash
asset main.js 142 bytes [compared for emit] [minimized] (name: main)
./src/index.js 30 bytes [built] [code generated]
./src/others.js 1 bytes [built] [code generated]
webpack 5.1.0 compiled successfully in 187 ms
```

```bash
npx webpack ./src/index.js ./src/others2.js --output-path dist/
```

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

```bash
asset main.js 142 bytes [compared for emit] [minimized] (name: main)
./src/index.js 30 bytes [built] [code generated]
./src/others2.js 1 bytes [built] [code generated]
./src/others.js 1 bytes [built] [code generated]
webpack 5.1.0 compiled successfully in 198 ms
```

## Default Configurations

CLI will look for some default configurations in the path of your project, here are the config files picked up by CLI.

This is the lookup priority in increasing order

> example - config file lookup will be in order of webpack.config.js > .webpack/webpack.config.js > .webpack/webpackfile.js

```text
'webpack.config',
'.webpack/webpack.config',
'.webpack/webpackfile',
```

Each base name is resolved against the supported extensions — JavaScript and TypeScript variants (`.js`, `.mjs`, `.cjs`, `.ts`, `.cts`, `.mts`), other supported languages such as `.coffee`, and, since webpack-cli 7.1.0, the [data formats](/configuration/configuration-languages/#data-formats-json5-yaml-and-toml) `.json5`, `.yaml`/`.yml` and `.toml`.

## Common Options

W> 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"`](/configuration/mode/#usage) to webpack CLI and your configuration file uses `development`, `production` will be used.

### help

**List basic commands and flags available on the cli**

Both `webpack help [command] [option]` and `webpack [command] --help` are valid to get help:

```bash
npx webpack --help

# or

npx webpack help
```

**List all supported commands and flags by cli**

```bash
npx webpack --help=verbose
```

**See help for a specific command or option**

```bash
npx webpack help --mode
```

### version

**Output the version number of 'webpack', 'webpack-cli' and 'webpack-dev-server' and other packages**

To inspect the version of `webpack` and `webpack-cli` you are using, run the command:

```bash
npx webpack --version

# or

npx webpack version
```

This will output the following result:

```bash
webpack 5.31.2
webpack-cli 4.6.0
```

It will output the version of `webpack-dev-server` as well if you have it installed:

```bash
webpack 5.31.2
webpack-cli 4.6.0
webpack-dev-server 3.11.2
```

### config

**Build source using a configuration file**

Specify a different [configuration](/configuration) file other than `webpack.config.js`, which is one of the defaults.

```bash
npx webpack --config example.config.js
```

### config-name

In case your configuration file exports multiple configurations, you can use `--config-name` to specify which configuration to run.

Consider the following `webpack.config.js`:

```js
export default [
  {
    output: {
      filename: "./dist-first.js",
    },
    name: "first",
    entry: "./src/first.js",
    mode: "development",
  },
  {
    output: {
      filename: "./dist-second.js",
    },
    name: "second",
    entry: "./src/second.js",
    mode: "development",
  },
  {
    output: {
      filename: "./dist-third.js",
    },
    name: "third",
    entry: "./src/third.js",
    mode: "none",
    stats: "verbose",
  },
];
```

To run only the `second` configuration:

```bash
npx webpack --config-name second
```

You can also pass multiple values:

```bash
npx webpack --config-name first --config-name second
```

### merge

You can merge two or more different webpack configurations with the help of `--merge`:

```bash
npx webpack --config ./first.js --config ./second.js --merge
```

### extends



You can extend existing webpack configurations with the help of `--extends`:

```bash
npx webpack --extends ./base.webpack.config.js
```

Read more about it in [extending configurations](/configuration/extending-configurations/).

### json

**Print result of webpack as JSON**

```bash
npx webpack --json
```

**If you want to store stats as json instead of printing it, you can use -**

```bash
npx 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](https://webpack.github.io/analyse/), or chrisbateman's [webpack-visualizer](https://chrisbateman.github.io/webpack-visualizer/), or th0r's [webpack-bundle-analyzer](https://github.com/webpack/webpack-bundle-analyzer). The analyse tool will take in the JSON and provide all the details of the build in graphical form.

T> See the [stats data api](/api/stats) to read more about the stats generated here.

## Environment Options

When the webpack configuration [exports a function](/configuration/configuration-types/#exporting-a-function), an "environment" may be passed to it.

### env

```bash
npx webpack --env production    # env.production = true
```

The `--env` argument accepts multiple values:

| Invocation                                                       | Resulting environment                          |
| ---------------------------------------------------------------- | ---------------------------------------------- |
| `npx webpack --env prod`                                         | `{ prod: true }`                               |
| `npx webpack --env prod --env min`                               | `{ prod: true, min: true }`                    |
| `npx webpack --env platform=app --env production`                | `{ platform: "app", production: true }`        |
| `npx webpack --env foo=bar=app`                                  | `{ foo: "bar=app"}`                            |
| `npx webpack --env app.platform="staging" --env app.name="test"` | `{ app: { platform: "staging", name: "test" }` |

T> If you want to explicitly set a variable to empty string (`""`), you may need to escape characters on terminal like `npx webpack --env foo=\"\"`

T> See the [environment variables](/guides/environment-variables/) guide for more information on its usage.

In addition to the customized `env` showed above, there are some built-in ones under `env` to be used inside your webpack configuration:

| Environment Variable | Description                                  |
| -------------------- | -------------------------------------------- |
| `WEBPACK_SERVE`      | `true` if `serve\|server\|s` is being used.  |
| `WEBPACK_BUILD`      | `true` if `build\|bundle\|b` is being used.  |
| `WEBPACK_WATCH`      | `true` if `--watch\|watch\|w` is being used. |

Note that you can not access those built-in environment variables inside the bundled code.

```js
export default (env, argv) => ({
  mode: env.WEBPACK_SERVE ? "development" : "production",
});
```

### config-node-env



Set `process.env.NODE_ENV` for your configuration:

```bash
npx webpack --config-node-env production   # process.env.NODE_ENV = 'production' in `webpack.config.js`
```

When the `mode` option is not specified in the configuration, you can use the `--config-node-env` option to set the `mode`. For example, using `--config-node-env production` will set both `process.env.NODE_ENV` and `mode` to `'production'`.

If your configuration exports a function, the value of `--config-node-env` is assigned to mode after the function returns. This means that `mode` will not be available in the function arguments (`env` and `argv`). However, the value of `--config-node-env` is accessible as `argv.nodeEnv` within the function and can be used accordingly.

```js
export default (env, argv) => {
  console.log(argv.defineProcessEnvNodeEnv); // 'production' if --config-node-env production is used
  return {
    // your configuration
  };
};
```

## Configuration Options

| Parameter       | Explanation                                                    | Input type | Default                                             |
| --------------- | -------------------------------------------------------------- | ---------- | --------------------------------------------------- |
| `--config`      | Path to the configuration file                                 | string[]   | [Default Configs](/api/cli/#default-configurations) |
| `--config-name` | Name of the configuration to use                               | string[]   |                                                     |
| `--env`         | Environment passed to the configuration, when it is a function | string[]   |                                                     |

## Analyzing Bundle

You can also use `webpack-bundle-analyzer` to analyze your output bundles emitted by webpack. You can use `--analyze` flag to invoke it via CLI.

```bash
npx webpack --analyze
```

W> Make sure you have `webpack-bundle-analyzer` installed in your project else CLI will prompt you to install it.

## Progress

To check the progress of any webpack compilation you can use the `--progress` flag.

```bash
npx webpack --progress
```

To collect profile data for progress steps you can pass `profile` as value to `--progress` flag.

```bash
npx webpack --progress=profile
```

## Pass CLI arguments to Node.js

To pass arguments directly to Node.js process, you can use the `NODE_OPTIONS` option.

For example, to increase the memory limit of Node.js process to 4 GB

```bash
NODE_OPTIONS="--max-old-space-size=4096" webpack
```

Also, you can pass multiple options to Node.js process

```bash
NODE_OPTIONS="--max-old-space-size=4096 -r /path/to/preload/file.js" webpack
```

## Exit codes and their meanings

| Exit Code | Description                                        |
| --------- | -------------------------------------------------- |
| `0`       | Success                                            |
| `1`       | Errors from webpack                                |
| `2`       | Configuration/options problem or an internal error |

## CLI Environment Variables

| Environment Variable                  | Description                                                         |
| ------------------------------------- | ------------------------------------------------------------------- |
| `WEBPACK_CLI_SKIP_IMPORT_LOCAL`       | when `true` it will skip using the local instance of `webpack-cli`. |
| `WEBPACK_CLI_FORCE_LOAD_ESM_CONFIG`   | when `true` it will force load the ESM config.                      |
| [`WEBPACK_PACKAGE`](#webpack_package) | Use a custom webpack version in CLI.                                |
| `WEBPACK_DEV_SERVER_PACKAGE`          | Use a custom webpack-dev-server version in CLI.                     |
| `WEBPACK_CLI_HELP_WIDTH`              | Use a custom width for help output.                                 |

```bash
WEBPACK_CLI_FORCE_LOAD_ESM_CONFIG=true npx webpack --config ./webpack.config.esm
```

### WEBPACK_PACKAGE

Use a custom webpack version in CLI. Considering the following content in your `package.json`:

```json
{
  "webpack": "^4.0.0",
  "webpack-5": "npm:webpack@^5.32.0",
  "webpack-cli": "^4.5.0"
}
```

To use `webpack v4.0.0`:

```bash
npx webpack
```

To use `webpack v5.32.0`:

```bash
WEBPACK_PACKAGE=webpack-5 npx webpack
```

## Troubleshooting

### TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for ./webpack.config.ts

You might encounter this error in the case of using native ESM in TypeScript (i.e. `type: "module"` in `package.json`).

`webpack-cli` supports configuration in both `CommonJS` and `ESM` format, at first it tries to load a configuration using `import()`, once it fails it would try to load the configuration using `require()`.
However, the `import()` method won't work with `ts-node` without [loader hooks](https://nodejs.org/api/esm.html#esm_experimental_loaders) enabled (described at [`TypeStrong/ts-node#1007`](https://github.com/TypeStrong/ts-node/issues/1007)).

To fix the error above use the following command:

```bash
NODE_OPTIONS="--import=data:text/javascript,import { register } from 'node:module'; import { pathToFileURL } from 'node:url'; register('ts-node/esm', pathToFileURL('./'));" npx webpack --entry ./src/index.js --mode production
```

For more information, see our documentation on [writing a webpack configuration in `TypeScript`](/configuration/configuration-languages/#typescript).

---

## File: src/content/api/compilation-hooks.mdx

---
title: Compilation Hooks
group: Plugins
sort: 10
contributors:
  - slavafomin
  - byzyk
  - madhavarshney
  - misterdev
  - wizardofhogwarts
  - EugeneHlushko
  - chenxsan
  - jamesgeorge007
  - snitin315
---

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:

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

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

W> Since webpack 5, `hooks` are no longer extendable. Use a `WeakMap` to add custom hooks.

## buildModule

`SyncHook`

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

- Callback Parameters: `module`

```js
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.

## optimizeDependencies

`SyncBailHook`

Fired at the beginning of dependency optimization.

- Callback Parameters: `modules`

## afterOptimizeDependencies

`SyncHook`

Fired after the dependency optimization.

- Callback Parameters: `modules`

## afterChunks

`SyncHook`



The `afterChunks` hook is invoked following the creation of the chunks and module graph, and prior to their optimization.
This hook provides an opportunity to examine, analyze, and modify the chunk graph if necessary.

Here's [an example](https://github.com/webpack/webpack/blob/10be3f9e3fb34078af8c5841a77025a6722f11bf/lib/wasm-sync/WebAssemblyModulesPlugin.js#L114-L137) of how to utilize the `compilation.hooks.afterChunks` hook.

- Callback Parameters: `chunks`

## optimize

`SyncHook`

Triggered at the beginning of the optimization phase.

## optimizeModules

`SyncBailHook`

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

- Callback Parameters: `modules`

## afterOptimizeModules

`SyncHook`

Called after modules optimization has completed.

- Callback Parameters: `modules`

## optimizeChunks

`SyncBailHook`

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

- 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`

## 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`

## afterOptimizeChunkModules

`SyncHook`

Called after the chunkmodules optimization has completed successfully.

- 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`](#record), [`recordModules`](#recordmodules), [`recordChunks`](#recordchunks) and [`recordHash`](#recordhash)).

## reviveModules

`SyncHook`

Restore module information from records.

- Callback Parameters: `modules` `records`

## 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`

## beforeChunkIds

`SyncHook`

Executed before assigning an `id` to each chunk.

- Callback Parameters: `chunks`

## chunkIds

`SyncHook`

Called to assign an `id` to each chunk.

- 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 triggered if [`shouldRecord`](#shouldrecord) returns a truthy value.

- Callback Parameters: `modules` `records`

## recordChunks

`SyncHook`

Store chunk info to the records. This is only triggered if [`shouldRecord`](#shouldrecord) returns a truthy value.

- Callback Parameters: `chunks` `records`

## beforeModuleHash

`SyncHook`

Called before modules are hashed.

## afterModuleHash

`syncHook`

Called after modules are hashed.

## 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`](#shouldrecord) returns a truthy value.

- Callback Parameters: `records`

## record

`SyncHook`

Store information about the `compilation` to the `records`. This is only triggered if [`shouldRecord`](#shouldrecord) returns a truthy value.

- Callback Parameters: `compilation` `records`

## beforeModuleAssets

`SyncHook`

Executed before module assets creation.

## additionalChunkAssets

`SyncHook`

W> `additionalChunkAssets` is deprecated (use the [Compilation.hook.processAssets](#processassets) instead and use one of the Compilation.PROCESS_ASSETS_STAGE\_\* as a stage option)

Create additional assets for the chunks.

- Callback Parameters: `chunks`

## shouldGenerateChunkAssets

`SyncBailHook`

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

## beforeChunkAssets

`SyncHook`

Executed before creating the chunks assets.

## additionalAssets

`AsyncSeriesHook`

W> `additionalAssets` is deprecated (use the [Compilation.hook.processAssets](#processassets) hook instead and use one of the Compilation.PROCESS_ASSETS_STAGE\_\* as a stage option)

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

```js
compilation.hooks.additionalAssets.tapAsync("MyPlugin", (callback) => {
  download("https://img.shields.io/npm/v/webpack.svg", (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`

W> `optimizeChunkAssets` is deprecated (use the [Compilation.hook.processAssets](#processassets) instead and use one of the Compilation.PROCESS_ASSETS_STAGE\_\* as a stage option)

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 adds a banner to each chunk.

```js
compilation.hooks.optimizeChunkAssets.tapAsync(
  "MyPlugin",
  (chunks, callback) => {
    for (const chunk of chunks) {
      for (const file of chunk.files) {
        compilation.assets[file] = new ConcatSource(
          "/**Sweet Banner**/",
          "\n",
          compilation.assets[file],
        );
      }
    }

    callback();
  },
);
```

## afterOptimizeChunkAssets

`SyncHook`

W> `afterOptimizeChunkAssets` is deprecated (use the [Compilation.hook.processAssets](#processassets) instead and use one of the Compilation.PROCESS_ASSETS_STAGE\_\* as a stage option)

The chunk assets have been optimized.

- Callback Parameters: `chunks`

Here's an example plugin from [@boopathi](https://github.com/boopathi) that outputs exactly what went into each chunk.

```js
compilation.hooks.afterOptimizeChunkAssets.tap("MyPlugin", (chunks) => {
  for (const chunk of chunks) {
    console.log({
      id: chunk.id,
      name: chunk.name,
      includes: chunk.getModules().map((module) => module.request),
    });
  }
});
```

## optimizeAssets

`AsyncSeriesHook`

W> `optimizeAssets` is deprecated (use the [Compilation.hook.processAssets](#processassets) hook instead)

Optimize all assets stored in `compilation.assets`.

- Callback Parameters: `assets`

## afterOptimizeAssets

`SyncHook`

W> `afterOptimizeAssets` is deprecated (use the [Compilation.hook.afterProcessAssets](#afterprocessassets) hook instead)

The assets have been optimized.

- Callback Parameters: `assets`

## processAssets

`AsyncSeriesHook`

Asset processing.

**Hook parameters:**

- `name: string` — a name of the plugin
- `stage: Stage` — a stage to tap into (see the [list of supported stages](#list-of-asset-processing-stages) below)
- `additionalAssets?: true | (assets, [callback]) => (void | Promise<void>)` — a callback for additional assets ([see below](#additional-assets))

**Callback parameters:**

- `assets: { [pathname: string]: Source }` — a plain object, where key is the asset's pathname, and the value is data of the asset represented by the [`Source`](https://github.com/webpack/webpack-sources#source).

**Example:**

```js
compilation.hooks.processAssets.tap(
  {
    name: "MyPlugin",
    stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS, // see below for more stages
  },
  (assets) => {
    console.log("List of assets and their sizes:");
    for (const [pathname, source] of Object.entries(assets)) {
      console.log(`— ${pathname}: ${source.size()} bytes`);
    }
  },
);
```

### Additional assets

In addition to `name` and `stage`, you can pass an `additionalAssets`  option which accepts either a value of `true` or a callback function that receives `assets` as a first argument:

1. `true` — run the provided callback again for assets added later by plugins.

   In this mode, the callback will be called multiple times: once for assets added prior to the specified stage, and additional times for assets added by plugins later (on this or next stages).

   ```js
   compilation.hooks.processAssets.tap(
     {
       name: "MyPlugin",
       stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
       additionalAssets: true,
     },
     (assets) => {
       // this function will be called multiple times with each bulk of assets
     },
   );
   ```

2. `(assets, [callback]) => (void | Promise<void>)` — run the specified callback against assets added by plugins later (on this or next stages). The callback must respect the type of the tap method used (e.g. when used with `tapPromise()`, it should return a promise).

   ```js
   compilation.hooks.processAssets.tap(
     {
       name: "MyPlugin",
       stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
       additionalAssets: (assets) => {
         // this function potentially could be called multiple times for assets added on later stages
       },
     },
     (assets) => {
       // this function will be called once with assets added by plugins on prior stages
     },
   );
   ```

### List of asset processing stages

Here's a list of supported stages (in the order of processing):

- `PROCESS_ASSETS_STAGE_ADDITIONAL` — add additional assets to the compilation.
- `PROCESS_ASSETS_STAGE_PRE_PROCESS` — basic preprocessing of the assets.
- `PROCESS_ASSETS_STAGE_DERIVED` — derive new assets from the existing assets.
- `PROCESS_ASSETS_STAGE_ADDITIONS` — add additional sections to the existing assets e.g. banner or initialization code.
- `PROCESS_ASSETS_STAGE_OPTIMIZE` — optimize existing assets in a general way.
- `PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT` — optimize the count of existing assets, e.g. by merging them.
- `PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY` — optimize the compatibility of existing assets, e.g. add polyfills or vendor prefixes.
- `PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE` — optimize the size of existing assets, e.g. by minimizing or omitting whitespace.
- `PROCESS_ASSETS_STAGE_DEV_TOOLING` — add development tooling to the assets, e.g. by extracting a source map.
- `PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE`  — optimize the numbers of existing assets, e.g. by inlining assets into other assets.
- `PROCESS_ASSETS_STAGE_SUMMARIZE` — summarize the list of existing assets.
- `PROCESS_ASSETS_STAGE_OPTIMIZE_HASH` — optimize the hashes of the assets, e.g. by generating real hashes of the asset content.
- `PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER` — optimize the transfer of existing assets, e.g. by preparing a compressed (gzip) file as separate asset.
- `PROCESS_ASSETS_STAGE_ANALYSE` — analyze the existing assets.
- `PROCESS_ASSETS_STAGE_REPORT` — creating assets for the reporting purposes.

### Assets info

The "asset info" metadata is not automatically provided for this hook. If needed, you will have to resolve this metadata manually using the compilation instance and the provided asset pathname. This will be improved in a future version of the webpack.

**Example:**

```js
compilation.hooks.processAssets.tap(
  {
    /** … */
  },
  (assets) => {
    for (const [pathname, source] of Object.entries(assets)) {
      const assetInfo = compilation.assetsInfo.get(pathname);
      // @todo: do something with "pathname", "source" and "assetInfo"
    }
  },
);
```

## afterProcessAssets

`SyncHook`

Called after the [`processAssets`](#processassets) hook had finished without error.

## 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 an asset needs to be processed further after being emitted.

## childCompiler

`SyncHook`

Executed after setting up a child compiler.

- Callback Parameters: `childCompiler` `compilerName` `compilerIndex`

## normalModuleLoader

Since webpack v5 `normalModuleLoader` hook was removed. Now to access the loader use `NormalModule.getCompilationHooks(compilation).loader` instead.

## statsPreset

`HookMap`

This HookMap is like a list of actions that gets triggered when a preset is used. It takes in an options object. When a plugin manages a preset, it should change settings in this object carefully without replacing existing ones.

- Callback Parameters: `options` `context`

Here's an illustrative plugin example:

```js
compilation.hooks.statsPreset.for("my-preset").tap("MyPlugin", (options) => {
  if (options.all === undefined) options.all = true;
});
```

This plugin ensures that for the preset `'my-preset'`, if the `all` option is undefined, it defaults to true.

## statsNormalize

`SyncHook`

This hook is used to transform an options object into a consistent format that can be easily used by subsequent hooks. It also ensures that missing options are set to their default values.

- Callback Parameters: `options` `context`

Here's an illustrative plugin example:

```js
compilation.hooks.statsNormalize.tap("MyPlugin", (options) => {
  if (options.myOption === undefined) options.myOption = [];

  if (!Array.isArray(options.myOption)) options.myOptions = [options.myOptions];
});
```

In this plugin, if the `myOption` is missing, it sets it to an empty array. Additionally, it ensures that `myOption` is always an array even if it was originally defined as a single value.

## statsFactory

This hook provides access to the [`StatsFactory` class](https://github.com/webpack/webpack/blob/main/lib/stats/StatsFactory.js) for specific options.

- Callback Parameters: `statsFactory` `options`

### StatsFactory.hooks.extract

`HookMap`

- Callback Parameters: `object` `data` `context`

`data` contains the class. object is an object to which properties should be added. `context` provides contextual information, such as classes on the path.

Example:

```js
compilation.hooks.statsFactory.tap("MyPlugin", (statsFactory, options) => {
  statsFactory.hooks.extract
    .for("compilation")
    .tap("MyPlugin", (object, compilation) => {
      object.customProperty = MyPlugin.getCustomValue(compilation);
    });
});
```

### StatsFactory.hooks.result

`HookMap`

Called with the result on each level.

- Callback Parameters: `result` `context`

## statsPrinter

This hook provides access to the [`StatsPrinter` class](https://github.com/webpack/webpack/blob/main/lib/stats/StatsPrinter.js) for specific options.

- Callback Parameters: `statsPrinter` `options`

### StatsPrinter.hooks.print

`HookMap`

This hook is called when a part should be printed.

- Callback Parameters: `object` `context`

### StatsPrinter.hooks.result

`HookMap`

This hook is called for the resulting string for a part.

- Callback Parameters: `result` `context`

## CssModulesPlugin.getCompilationHooks(compilation)

When [`experiments.css`](/configuration/experiments/#experimentscss) is enabled, the internal `CssModulesPlugin` exposes a set of per-compilation hooks for plugin authors. Access them via the static `getCompilationHooks(compilation)` method:

```js
const webpack = require("webpack");

class MyCssPlugin {
  apply(compiler) {
    compiler.hooks.thisCompilation.tap("MyCssPlugin", (compilation) => {
      const hooks =
        webpack.css.CssModulesPlugin.getCompilationHooks(compilation);
      // tap into hooks here
    });
  }
}
```

W> These hooks are only registered when `experiments.css` is enabled and may evolve while the CSS feature is experimental.

### orderModules



`SyncBailHook<[Chunk, Module[], Compilation], Module[] | undefined>`

Called once per CSS source type (CSS imports and CSS modules) with the chunk's modules pre-sorted by full module name. Taps may return an ordered `Module[]` to override webpack's default import-order topological sort, or return `undefined` to keep the default order.

The hook is the recommended escape hatch when webpack's topological sort surfaces a `Conflicting order between css ...` warning that cannot be resolved by restructuring imports. Returning the pre-sorted array (or any deterministic order) lets the build pick a stable order without changing application code.

- Callback Parameters: `chunk` `modules` `compilation`

```js
const webpack = require("webpack");

class CssOrderByPathPlugin {
  apply(compiler) {
    compiler.hooks.thisCompilation.tap(
      "CssOrderByPathPlugin",
      (compilation) => {
        const hooks =
          webpack.css.CssModulesPlugin.getCompilationHooks(compilation);

        // Modules arrive pre-sorted by full module name; return as-is to
        // enforce a deterministic file-path order across rebuilds and
        // side-step the conflicting-order warning.
        hooks.orderModules.tap(
          "CssOrderByPathPlugin",
          (_chunk, modules) => modules,
        );
      },
    );
  }
}
```

The hook is a `SyncBailHook`, so the first tap to return a non-`undefined` value wins. Subsequent taps are not invoked for that call.

## HtmlModulesPlugin.getCompilationHooks(compilation)



When [`experiments.html`](/configuration/experiments/#experimentshtml) is enabled, the internal `HtmlModulesPlugin` exposes a set of per-compilation hooks for injecting and transforming the emitted HTML pages. Access them via the static `getCompilationHooks(compilation)` method:

```js
const webpack = require("webpack");

class MyHtmlPlugin {
  apply(compiler) {
    compiler.hooks.thisCompilation.tap("MyHtmlPlugin", (compilation) => {
      const hooks =
        webpack.html.HtmlModulesPlugin.getCompilationHooks(compilation);
      // tap into hooks here
    });
  }
}
```

W> These hooks are only registered when `experiments.html` is enabled and may evolve while the HTML feature is experimental.

### injectTags

`AsyncSeriesWaterfallHook<[HtmlTagDescriptor[], { outputName, html }]>`

Called with the list of extra tags to inject into each page (initially empty) plus the current HTML. Push descriptors and return the list; webpack serializes and places them. It runs before [`output.html.csp`](/configuration/output/#outputhtmlcsp), so injected inline `<script>` / `<style>` tags are hashed like the page's own.

Each `HtmlTagDescriptor` accepts:

- `tag` (`string`): tag name, e.g. `'script'` / `'link'` / `'meta'`.
- `attrs` (`object`): attributes; `true` renders a bare boolean attribute, `false` / `undefined` omits it.
- `children` (`string`): inner content (ignored for void elements like `<link>` / `<meta>`).
- `injectTo` (`'head' | 'body' | 'head-prepend' | 'body-prepend'`): placement, defaults to `'head'`.
- `voidTag` (`boolean`): force a void element (no closing tag); inferred from the tag name when omitted.

```js
hooks.injectTags.tap("MyHtmlPlugin", (tags) => {
  tags.push({
    tag: "meta",
    attrs: { name: "theme-color", content: "#2b3a42" },
  });
  return tags;
});
```

### transformTags

`AsyncSeriesHook<[HtmlMutableTag[], { outputName, html }]>`

Called with the page's existing `<script>` / `<link>` / `<style>` / `<meta>` tags (webpack's own and any injected) as mutable descriptors. Mutate `attrs` (add a `nonce` / `data-*` attribute, switch `defer` and `async`, ...), set `remove: true`, or change `injectTo` to move a tag between `<head>` and ``; webpack rewrites the changed tags. Add new tags with [`injectTags`](#injecttags) instead, and don't reorder the array itself.

### transformHtml

`AsyncSeriesWaterfallHook<[string, { outputName: string }]>`

Called with each emitted page's final HTML (all placeholders resolved) just before it is written. Return the (possibly transformed) HTML, e.g. to minify it:

```js
hooks.transformHtml.tapPromise("MyHtmlPlugin", async (html, { outputName }) =>
  html.replace("", "..."),
);
```

### htmlEmitted

`AsyncSeriesHook<[{ outputName: string }]>`

Called once each page's HTML asset has been finalized — a post-emit notification.

---

## File: src/content/api/compilation-object.mdx

---
title: Compilation Object
group: Objects
sort: 14
contributors:
  - EugeneHlushko
  - wizardofhogwarts
  - jamesgeorge007
  - snitin315
---

The Compilation object has many methods and hooks available. 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, callback)`

Adds a module to the current compilation.

Parameters:

- `module` - module to be added
- `callback` - a callback after the module has been added

### getModule

`function (module)`

Fetches a module from a compilation by its identifier.

Parameters:

- `module` - module to be fetched. The 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. The identifier is extracted from the module by the compilation using `module.identifier()` method.

### 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.

### addEntry

`function (context, entry, name, callback)`

Adds an entry to the compilation.

Parameters:

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

### 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 the 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 the compilation has been unsealed.

### reportDependencyErrorsAndWarnings

`function (module, blocks)`

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

Parameters:

- `module` - the module whose errors and warnings are to be reported.
- `blocks` - a set of dependency 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 dependency 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 that are processed.

### removeReasonsOfDependencyBlock

`function (module, block)`

Removes relation of the module to the 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 dependency 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 dependencies block module and chunks after removing dependency reasons. Called automatically by `removeReasonsOfDependencyBlock`.

Parameters:

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

### sortItemsWithChunkIds

`function`

### summarizeDependencies

`function`

### createHash

`function`

### createModuleAssets

`function`

### createChunkAssets

`function`

### getPath

`function (filename, data)`

Returns the interpolated path.

Parameters:

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

### getPathWithInfo

`function (filename, data)`

Returns interpolated path and asset information.

Parameters:

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

### createChildCompiler

`function (name, outputOptions, plugins)`

Allows running another instance of webpack inside of webpack. However, as a child with different settings and configurations applied. It copies all hooks and plugins from the 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 = {})`

Parameters:

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

### updateAsset

`function (file, newSourceOrFunction, assetInfoUpdateOrFunction)`

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

### deleteAsset

`function (file)`

Parameters:

- `file` - file name of the asset

### getAssets

`function`

Returns array of all assets under the current compilation.

### getAsset

`function (name)`

Parameters:

- `name` - the name of the asset to return

---

## File: src/content/api/compiler-hooks.mdx

---
title: Compiler Hooks
group: Plugins
sort: 9
contributors:
  - rishantagarwal
  - byzyk
  - madhavarshney
  - misterdev
  - EugeneHlushko
  - superburrito
  - chenxsan
  - snitin315
---

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

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.

W> Since webpack 5, `hooks` are no longer extendable. Use a `WeakMap` to add custom hooks.

## Watching

The `Compiler` supports [watching](/api/node/#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](/guides/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](/api/cli/#watch-options).

## Hooks

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

```js
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](https://github.com/webpack/tapable#tapable).

### environment

`SyncHook`

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

### afterEnvironment

`SyncHook`

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

### entryOption

`SyncBailHook`

Called after the [`entry` configuration](/configuration/entry-context/#entry) from webpack options has been processed.

- Callback Parameters: [`context`](/configuration/entry-context/#context), [`entry`](/configuration/entry-context/#entry)

```js
compiler.hooks.entryOption.tap("MyPlugin", (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`

### validate

`SyncHook`



Called to register validation work for webpack configuration, plugins, and loaders. Plugin authors can tap this hook and use `compiler.validate(...)` to participate in webpack's built-in validation flow.

W> The hook is always available. `compiler.validate(...)` skips validation when `validate: false` is set. With `experiments.futureDefaults`, webpack keeps validation enabled by default in development and disables it by default in production.

```js
compiler.hooks.validate.tap("MyPlugin", () => {
  compiler.validate(
    () => require("./schema/MyPlugin.json"),
    options,
    { name: "My Plugin", baseDataPath: "options" },
    (validatedOptions) => require("./schema/MyPlugin.check")(validatedOptions),
  );
});
```

### initialize

`SyncHook`

Called when a compiler object is initialized.

### beforeRun

`AsyncSeriesHook`

Adds a hook right before running the compiler.

- Callback Parameters: `compiler`

### run

`AsyncSeriesHook`

Hook into the compiler before it begins reading [`records`](/configuration/other-options/#recordspath).

- 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](/api/normalmodulefactory-hooks) is created.

- Callback Parameters: `normalModuleFactory`

### contextModuleFactory

`SyncHook`

Runs a plugin after a [ContextModuleFactory](/api/contextmodulefactory-hooks) 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:

```js
compilationParams = {
  normalModuleFactory,
  contextModuleFactory,
};
```

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

```js
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. This hook is _not_ copied to child compilers.

- Callback Parameters: `compilationParams`

### thisCompilation

`SyncHook`

Executed while initializing the compilation, right before emitting the `compilation` event. This hook is _not_ copied to child compilers.

- 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. This hook is _not_ copied to child compilers.

- 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`

```js
compiler.hooks.shouldEmit.tap(
  "MyPlugin",
  (compilation) =>
    // return true to emit the output, otherwise false
    true,
);
```

### emit

`AsyncSeriesHook`

Executed right before emitting assets to output dir. This hook is _not_ copied to child compilers.

- Callback Parameters: `compilation`

### afterEmit

`AsyncSeriesHook`

Called after emitting assets to output directory. This hook is _not_ copied to child compilers.

- Callback Parameters: `compilation`

### assetEmitted

`AsyncSeriesHook`

Executed when an asset has been emitted. Provides access to information about the emitted asset, such as its output path and byte content.

- Callback Parameters: `file`, `info`

For example, you may access the asset's content buffer via `info.content`:

```js
compiler.hooks.assetEmitted.tap(
  "MyPlugin",
  (file, { content, source, outputPath, compilation, targetPath }) => {
    console.log(content); // 
  },
);
```

### done

`AsyncSeriesHook`

Executed when the compilation has completed. This hook is _not_ copied to child compilers.

- Callback Parameters: `stats`

### additionalPass

`AsyncSeriesHook`

This hook allows you to do a one more additional pass of the build.

### failed

`SyncHook`

Called if the compilation fails.

- Callback Parameters: `error`

### invalid

`SyncHook`

Executed when a watching compilation has been invalidated. This hook is _not_ copied to child compilers.

- Callback Parameters: `fileName`, `changeTime`

### watchClose

`SyncHook`

Called when a watching compilation has stopped.

### shutdown

`AsyncSeriesHook`

Called when the compiler is closing.

### infrastructureLog

`SyncBailHook`

Allows to use infrastructure logging when enabled in the configuration via [`infrastructureLogging` option](/configuration/infrastructureLogging/).

- Callback Parameters: `name`, `type`, `args`

### log

`SyncBailHook`

Allows to log into [stats](/configuration/stats/) when enabled, see [`stats.logging`, `stats.loggingDebug` and `stats.loggingTrace` options](/configuration/infrastructureLogging/).

- Callback Parameters: `origin`, `logEntry`

---

## File: src/content/api/contextmodulefactory-hooks.mdx

---
title: ContextModuleFactory Hooks
group: Plugins
sort: 11
contributors:
  - iguessitsokay
---

The `ContextModuleFactory` module is used by the `Compiler` to generate dependencies from webpack specific [require.context](/api/module-methods/#requirecontext) API. It resolves the requested directory, generates requests for each file and filters against passed regExp. Matching dependencies then passes through [NormalModuleFactory](/api/normalmodulefactory-hooks).

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

```js
ContextModuleFactory.hooks.someHook.tap(/* ... */);
```

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

## beforeResolve

`AsyncSeriesWaterfallHook`

Called before resolving the requested directory. The request can be ignored by returning `false`.

- Callback Parameters: `data`

## afterResolve

`AsyncSeriesWaterfallHook`

Called after the requested directory resolved.

- Callback Parameters: `data`

## contextModuleFiles

`SyncWaterfallHook`

Called after directory contents are read. On recursive mode, calls for each sub-directory as well. Callback parameter is an array of all file and folder names in each directory.

- Callback Parameters: `fileNames`

## alternativeRequests

`AsyncSeriesWaterfallHook`

Called for each file after the request is created but before filtering against regExp.

- Callback Parameters: `request` `options`

---

## File: src/content/api/hot-module-replacement.mdx

---
title: Hot Module Replacement
sort: 4
contributors:
  - sokra
  - skipjack
  - tbroadley
  - byzyk
  - wizardofhogwarts
  - snitin315
related:
  - title: Concepts - Hot Module Replacement
    url: /concepts/hot-module-replacement
  - title: Guides - Hot Module Replacement
    url: /guides/hot-module-replacement
---

If [Hot Module Replacement](/concepts/hot-module-replacement) has been enabled via the [`HotModuleReplacementPlugin`](/plugins/hot-module-replacement-plugin), its interface will be exposed under the [`module.hot`](/api/module-variables/#modulehot-webpack-specific) property as well as [`import.meta.webpackHot`](/api/module-variables/#importmetawebpackhot) property. Note that only `import.meta.webpackHot` can be used in [strict ESM](/guides/ecma-script-modules/#flagging-modules-as-esm).

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:

```js
if (module.hot) {
  module.hot.accept("./library.js", () => {
    // Do something with the updated library module...
  });
}

// or
if (import.meta.webpackHot) {
  import.meta.webpackHot.accept("./library.js", () => {
    // 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, in addition, you can attach an optional error handler:

```js
module.hot.accept(
  dependencies, // Either a string or an array of strings
  callback, // Function to fire when the dependencies are updated
  errorHandler, // (err, {moduleId, dependencyId}) => {}
);

// or
import.meta.webpackHot.accept(
  dependencies, // Either a string or an array of strings
  callback, // Function to fire when the dependencies are updated
  errorHandler, // (err, {moduleId, dependencyId}) => {}
);
```

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.

#### errorHandler for accept

`(err, {moduleId, dependencyId}) => {}`

- `err`: the error thrown by the callback in second argument or during dependency execution when using ESM dependencies.
- `moduleId`: the current module id.
- `dependencyId`: the module id of the (first) changed dependency.

### accept (self)

Accept updates for itself.

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

// or
import.meta.webpackHot.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.

#### errorHandler for self accept

`(err, {moduleId, module}) => {}`

- `err`: the error when evaluating the new version.
- `moduleId`: the current module id.
- `module`: the current module instance.
  - `module.hot`: allow to use the HMR API of the errored module instance. A common scenario is to self accept it again. It also makes sense to add a dispose handler to pass data along. Note that the errored module might be already partially executed, so make sure to not get into a inconsistent state. You can use `module.hot.data` to store partial state.
  - `module.exports`: can be overridden, but be careful since property names might be mangled in production mode.

### decline

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

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

// or
import.meta.webpackHot.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't 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.

```js
module.hot.decline();

// or
import.meta.webpackHot.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.

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

// or
import.meta.webpackHot.dispose((data) => {
  // Clean up and pass data to the updated module...
});
```

### invalidate

Calling this method will invalidate the current module, which disposes and recreates it when the HMR update is applied. This bubbles like a normal update of this module. `invalidate` can't be self-accepted by this module.

When called during the `idle` state, a new HMR update will be created containing this module. HMR will enter the `ready` state.

When called during the `ready` or `prepare` state, this module will be added to the current HMR update.

When called during the `check` state, this module will be added to the update when an update is available. If no update is available it will create a new update. HMR will enter the `ready` state.

When called during the `dispose` or `apply` state, HMR will pick it up after getting out of those states.

#### Use Cases

**Conditional Accepting**

A module can accept a dependency, but can call `invalidate` when the change of the dependency is not handleable:

```js
import { processX, processY } from "anotherDep";
import { x, y } from "./dep";

const oldY = y;

processX(x);

export default processY(y);

module.hot.accept("./dep", () => {
  if (y !== oldY) {
    // This can't be handled, bubble to parent
    module.hot.invalidate();
    return;
  }
  // This can be handled
  processX(x);
});
```

**Conditional self accept**

A module can self-accept itself, but can invalidate itself when the change is not handleable:

```js
const VALUE = "constant";

export default VALUE;

if (
  module.hot.data &&
  module.hot.data.value &&
  module.hot.data.value !== VALUE
) {
  module.hot.invalidate();
} else {
  module.hot.dispose((data) => {
    data.value = VALUE;
  });
  module.hot.accept();
}
```

**Triggering custom HMR updates**

{/* eslint-disable no-eval */}

```js
const moduleId = chooseAModule();
const code = __webpack_modules__[moduleId].toString();
__webpack_modules__[moduleId] = eval(`(${makeChanges(code)})`);
if (require.cache[moduleId]) {
  require.cache[moduleId].hot.invalidate();
  module.hot.apply();
}
```

T> When `invalidate` is called, the [`dispose`](#dispose-or-adddisposehandler) handler will be eventually called and fill `module.hot.data`. If [`dispose`](#dispose-or-adddisposehandler) handler is not registered, an empty object will be supplied to `module.hot.data`.

W> Do not get caught in an `invalidate` loop, by calling `invalidate` again and again. This will result in stack overflow and HMR entering the `fail` state.

### removeDisposeHandler

Remove the handler added via `dispose` or `addDisposeHandler`.

```js
module.hot.removeDisposeHandler(callback);

// or
import.meta.webpackHot.removeDisposeHandler(callback);
```

## Management API

### status

Retrieve the current status of the hot module replacement process.

```js
module.hot.status(); // Will return one of the following strings...

// or
import.meta.webpackHot.status();
```

| Status  | Description                                                                         |
| ------- | ----------------------------------------------------------------------------------- |
| idle    | The process is waiting for a call to [`check`](#check)                              |
| check   | The process is checking for updates                                                 |
| prepare | The process is getting ready for the update (e.g. downloading the updated module)   |
| ready   | The update is prepared and available                                                |
| dispose | The process is calling the `dispose` handlers on the modules that will be replaced  |
| apply   | The process is calling the `accept` handlers and re-executing self-accepted modules |
| abort   | An update was aborted, but the system is still in its previous state                |
| fail    | 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.

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

// or
import.meta.webpackHot
  .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'`).

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

// or
import.meta.webpackHot
  .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:

```ts
{
  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`.

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

// or
import.meta.webpackHot.addStatusHandler((status) => {
  // React to the current status...
});
```

Bear in mind that when the status handler returns a `Promise`, the HMR system will wait for the `Promise` to resolve before continuing.

### removeStatusHandler

Remove a registered status handler.

```js
module.hot.removeStatusHandler(callback);

// or
import.meta.webpackHot.removeStatusHandler(callback);
```