Command Line Interface

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.

⚡ Quick Start

Most commonly used commands:

  • Production build

    npx webpack --mode production
  • Start development server

    npx webpack serve --open
  • Watch for file changes

    npx webpack --watch
  • Run with config file

    npx webpack --config webpack.config.js

💡 Tip: Use serve during development instead of watch for live reload.

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

⚠️ Requirements

  • Node.js >= 20.9.0
  • webpack >= 5.101.0
  • webpack-dev-server >= 5.0.0

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.

Execution Commands

By default webpack ships with the following commands:

CommandPurpose
buildCreate production bundle
serveStart dev server (hot reload)
watchRebuild on file changes
infoShow system/debug info
configtestValidate config
versionShow package versions
helpShow help for commands and flags

Project Scaffolding

These commands use the create-webpack-app package.

ℹ️ These commands may prompt you to install create-webpack-app if not already installed.

Scaffolding-related commands:

CommandUsageDescription
initinit [generation-path] [options]Initialize a new webpack project using create-webpack-app.
loaderloader [output-path] [options]Scaffold a loader.
pluginplugin [output-path] [options]Scaffold a plugin.

When should I use each command?

  • build → Create a production-ready bundle
  • serve → Run development server with live reload
  • watch → Rebuild automatically without dev server
  • configtest → Validate configuration file
  • info → Debug environment issues

Build

Run webpack (default command, can be omitted).

npx webpack build [options]

example

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

Init

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

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

example

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

Alias to:

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.

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

example

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.

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

example

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.

Info

Outputs information about your system.

npx webpack info [options]

example

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

Options for info

-a, --additional-package

string

Adds additional packages to the output.

example

npx webpack info --additional-package postcss

-o, --output

string : 'json' | 'markdown'

To get the output in a specified format.

example

npx webpack info --output markdown

Configtest

Validate a webpack configuration.

npx webpack configtest [config-path]

example

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.

npx webpack serve [options]

example

npx webpack serve --static --open

Watch

Run webpack and watch for files changes.

npx webpack watch [options]

example

npx webpack watch --mode development

Flags

Basic Flags

FlagDescription
--modeSet development or production mode
--config, -cSpecify config file
--watch, -wEnable watch mode
--progressShow build progress

Input / Output

FlagDescription
--entryEntry point
--output-path, -oOutput directory
--target, -tBuild target

Development & Debugging

FlagDescription
--devtool, -dSource maps
--statsControl output stats
--json, -jOutput JSON stats
--analyzeAnalyze bundle

Advanced

FlagDescription
--envPass environment variables
--config-nameSelect config
--merge, -mMerge configs
--extends, -eExtend config

CLI Behavior

FlagDescription
--colorEnable colors
--helpShow help
--version, -vShow version

Full flag reference

By default webpack also ships with the following flags:

Flag / AliasTypeDescription
--entrystring[]The entry point(s) of your application e.g. ./src/main.js
--config, -cstring[]Provide path to a webpack configuration file e.g. ./webpack.config.js
--config-namestring[]Name of the configuration to use
--namestringName of the configuration. Used when loading multiple configurations
--colorbooleanEnable colors on console
--merge, -mbooleanMerge two or more configurations using webpack-merge
--envstring[]Environment passed to the configuration when it is a function
--config-node-envstringSet process.env.NODE_ENV to the specified value
--progressboolean, stringPrint compilation progress during build
--helpbooleanOutputs list of supported flags and commands
--output-path, -ostringOutput location of the file generated by webpack e.g. ./dist
--target, -tstring[]Sets the build target
--watch, -wbooleanWatch for file changes
--watch-options-stdinbooleanStop watching when stdin stream has ended
--devtool, -dstringControls if and how source maps are generated.
--json, -jboolean, stringPrints result as JSON or store it in a file
--modestringDefines the mode to pass to webpack
--version, -vbooleanGet current version
--statsboolean, stringIt instructs webpack on how to treat the stats
--disable-interpretbooleanDisable interpret for loading the config file.
--fail-on-warningsbooleanStop webpack-cli process with non-zero exit code on warnings from webpack
--analyzebooleanIt invokes webpack-bundle-analyzer plugin to get bundle information
--extends, -estring[]Extend an existing configuration

Negated Flags

FlagDescription
--no-colorDisables any color on the console
--no-hotDisables hot reloading if you have it enabled via your config
--no-statsDisables any compilation stats emitted by webpack
--no-watchDo not watch for file changes
--no-devtoolDo not generate source maps
--no-watch-options-stdinDo 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

For example if you want to enable performance hints in your project you'd use this option in configuration, with core flags you can do -

npx webpack --performance-hints warning

How CLI maps to configuration

Most CLI options map directly to webpack.config.js.

example

npx webpack --output-path dist

Equivalent config:

module.exports = {
  output: {
    path: "dist",
  },
};

Common Use Cases

Build for production

npx webpack --mode production

Development with live reload

npx webpack serve --mode development --open

Debug configurations

npx webpack configtest
```

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

### Example: Before vs After

Without `--entry-reset`:

```bash
npx webpack --entry ./new.js
```

Adds to existing entries.

With `--entry-reset`:

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

Replaces all previous 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',
```

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

<Badge text="webpack-cli v5.1.0+" />

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

Result:

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

<Badge text="webpack-cli v6.0.0+" />

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

You can also 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
```

---

## Using Webpack with TypeScript & ESM

Node.js requires a loader hook to understand `.ts` files when using ESM.

### 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).
Edit this page·

17 Contributors

anshumanvrishabh3112snitin315evenstensbergsimon04tbroadleychenxsanrenciremadhavarshneyEugeneHlushkobyzykwizardofhogwartsEslamHikosmelukovanikethsahajamesgeorge007burhanuday