Targets

Because JavaScript can be written for both server and browser, webpack offers multiple deployment targets that you can set in your webpack configuration.

Usage

To set the target property, you set the target value in your webpack config:

webpack.config.js

export default {
  target: "node",
};

In the example above, using node webpack will compile for usage in a Node.js-like environment (uses Node.js require to load chunks and not touch any built in modules like fs or path).

Each target has a variety of deployment/environment specific additions, support to fit its needs. See what targets are available.

Multiple Targets

webpack supports passing an array of strings to the target property, in which case the common subset of their features is used. This lets you build universal code that runs in multiple environments — for example, combine web and node:

webpack.config.js

export default {
  target: ["web", "node"],
};

Alternatively, you can create an isomorphic library by bundling two separate configurations:

webpack.config.js

import path from "node:path";
import { fileURLToPath } from "node:url";

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

const serverConfig = {
  target: "node",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "lib.node.js",
  },
  // …
};

const clientConfig = {
  target: "web", // <=== can be omitted as default is 'web'
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "lib.js",
  },
  // …
};

export default [serverConfig, clientConfig];

The example above will create a lib.js and lib.node.js file in your dist folder.

Resources

As seen from the options above, there are multiple deployment targets that you can choose from. Below is a list of examples and resources that you can refer to.

Edit this page·

6 Contributors

TheLarkInnrouzbeh84johnstewsrilmanbyzykEugeneHlushko