Configuration: entry, output and mode

webpack · Essentials · 12 min

Every webpack project starts from this skeleton.

webpack.config.js exports a configuration object (or a function returning one). The essentials:

  • entry: a string, an array, or an object of named entries, e.g. { app: "./src/app.js", admin: "./src/admin.js" } for two separate bundles.
  • output.path: an absolute directory, usually path.resolve(__dirname, "dist").
  • output.filename: a template with placeholders: [name] (entry or chunk name), [contenthash] (hash of the file's content, for caching), [id]. For example [name].[contenthash].js.
  • output.clean: true: empty the output directory before each build.
  • output.publicPath: the URL prefix where assets will be served ("/" or "auto").
  • mode: "development" (readable output, fast rebuilds, helpful errors) or "production" (minification with Terser, tree shaking, scope hoisting, process.env.NODE_ENV set to "production"). Without a mode, webpack warns and assumes production.

Run with npx webpack (reads webpack.config.js), npx webpack --config other.config.js, or npx webpack --mode development. Put commands in npm scripts.

Exporting a function (env, argv) => config lets one file handle several modes: argv.mode holds the CLI mode and --env foo=bar arrives as env.foo.

Example

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

module.exports = (env, argv) => ({
  mode: argv.mode ?? "development",
  entry: {
    app: "./src/index.js",
    admin: "./src/admin.js",
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: argv.mode === "production" ? "[name].[contenthash].js" : "[name].js",
    clean: true,          // wipe dist/ before each build
    publicPath: "/",
  },
});

// package.json scripts:
//   "build": "webpack --mode production",
//   "build:dev": "webpack --mode development"
// $ npm run build
// asset app.3f1c2a9b8e7d6c5b.js 1.2 KiB [emitted] [immutable] [minimized] (name: app)
// asset admin.a9e8d7c6b5a4f3e2.js 980 bytes [emitted] [immutable] [minimized] (name: admin)

Remember

  • entry names bundles; output.path must be absolute
  • [name] and [contenthash] placeholders in filenames
  • mode switches on dev or production defaults
  • Export a function to vary config by mode and --env

Watch out for

  • Omitting mode, getting a warning and production defaults during development.

Check yourself

  1. Why use `[contenthash]` in production filenames?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: webpack.js.org/concepts/output/