Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

The Webpack Configuration File

Understand webpack.config.js: its main keys, CommonJS versus ESM and TypeScript configs, exporting a function or array, passing env flags and validating your configuration.

Zero-config builds are handy for a first try, but real projects need a configuration file. By default Webpack reads webpack.config.js from the folder where you run it. The file exports a plain JavaScript object (or something that produces one), so you can use variables, require, conditions and functions to build it.

The smallest useful config

JavaScript
// webpack.config.js
const path = require('node:path');

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    clean: true,
  },
};

Three things to notice:

  • path must be an absolute path. path.resolve(__dirname, 'dist') builds one from the config file's location, so the build works from any working directory.
  • entry is a path relative to the project (the context, by default the current directory).
  • clean: true empties dist before each build, so old files do not pile up.

The top-level keys

A configuration has a handful of top-level keys. You will meet each one in this course.

Key Purpose Lesson
mode development, production or none Build Modes
entry where the graph starts Entry Points
output where and how files are written Output and Filenames
module.rules loaders for non-JS files Loaders Basics
plugins extra build steps HTML Webpack Plugin
resolve how import paths are found Resolve and Aliases
devServer the development server Dev Server
devtool source maps Source Maps
optimization minimizing, chunk splitting Chapter 6
flowchart LR
  C["webpack.config.js"] --> E["entry"]
  C --> O["output"]
  C --> M["module.rules"]
  C --> P["plugins"]
  C --> R["resolve"]
  C --> D["devServer / devtool"]

One object, a few well-defined sections.

Config file formats

Webpack can load the config in several formats, which matter once your package uses ES modules.

JavaScript
// webpack.config.mjs (ESM, or .js with "type": "module" in package.json)
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export default {
  entry: './src/index.js',
  output: { path: path.resolve(__dirname, 'dist') },
};

With the ts-node package installed you can also write webpack.config.ts and get type checking from the Configuration type. To use a file with another name, run webpack --config webpack.prod.js.

Export a function to receive flags

A config can be a function that receives env (values from --env) and argv (the CLI options, including --mode). This is how one file supports several builds.

JavaScript
module.exports = (env, argv) => {
  const isProd = argv.mode === 'production';
  return {
    mode: argv.mode ?? 'development',
    devtool: isProd ? false : 'source-map',
    output: { filename: isProd ? '[name].[contenthash].js' : '[name].js' },
    plugins: env.analyze ? [new BundleAnalyzerPlugin()] : [],
  };
};

Run it with webpack --mode production --env analyze. The --env flag turns analyze into env.analyze === true; --env target=legacy gives env.target === 'legacy'.

You can also export an array of configs, which builds several bundles in one run, for example a browser build and a server build.

Node.js Stand-in: a config function with flags

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

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

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

Defaults and validation

Webpack fills in thousands of defaults (for example resolve.extensions, target, output.path) and validates your object against a schema. A typo such as entery or module.rule stops the build with a precise message:

TEXT
[webpack-cli] Invalid configuration object. Webpack has been initialized
using a configuration object that does not match the API schema.
 - configuration has an unknown property 'entery'.

Fix the key and run again. Use webpack --help or the TypeScript type to see valid keys.

Node.js Stand-in: catch typos like the schema validator does

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

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

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

The real validator is more detailed, but the principle is the same: fail early and name the bad key.

Split configs for dev and production

Large projects often keep three files: webpack.common.js for shared settings, plus webpack.dev.js and webpack.prod.js. The package webpack-merge combines them:

JavaScript
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, { mode: 'production', devtool: false });

Either approach works. A single function-based file is simpler for small apps; split files scale better when the two builds differ a lot.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use path.resolve(__dirname, 'dist') for output.path?

    output.path must be absolute, and __dirname anchors it to the config file's folder.
  2. 2. What does exporting a function from webpack.config.js give you?

    Webpack calls the function with (env, argv), so one file can produce different builds.
  3. 3. What happens if the config has an unknown key like 'entery'?

    Webpack validates the configuration against its schema and reports the unknown property.
  4. 4. Which command uses a differently named config file?

    The --config option selects the file.

Summary

  • webpack.config.js exports an object, a function of (env, argv), or an array of configs.
  • output.path must be absolute; use path.resolve(__dirname, ...).
  • The main keys are mode, entry, output, module.rules, plugins, resolve, devServer, devtool, optimization.
  • ESM (.mjs) and TypeScript configs are supported; --config picks another file.
  • The schema validator rejects unknown keys, and webpack-merge combines shared and per-environment configs.

Next: Build Modes: Development, Production and None