user11687621
user11687621

Reputation:

Webpack How to use the Target Attribute

I am new to Webpack and I am trying to figure out what target actually does.

In the docs, Webpack says:

Node: Compile for usage in a Node.js-like environment (uses Node.js require to load chunks)

Web: Compile for usage in a browser-like environment (default)

But it is very abstract and does not tell what is the actual difference.

I notice that if a run the webpack config file with webpack-server in node mode, I get the error required is not defined, whereas if I just use webpack to export the files and then run the files independently, it runs fine. Does the target apply only to the webpack dev server?

module.exports = {
  mode: "development",
  target: "web", //node
  devtool: "cheap-module-source-map",
  entry: "./src/index",
  output: {
    path: path.resolve(__dirname, "build"),
    publicPath: "/",
    filename: "./bundle.js"
  },
  devServer: {
    stats: "minimal",
    overlay: true,
    historyApiFallback: true,
    disableHostCheck: true,
    headers: { "Access-Control-Allow-Origin": "*" },
    https: false
  },
}

I set the target attribute to "web" and ran it from backend. There is no difference with the target "node". It runs just fine. I see no purpose of the attribute

Upvotes: 5

Views: 12772

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

A very very simple example would be,

let's say you are creating a React app, which is a client side application and will be run at browser. You set the target to be web. (this is the default one)

If let's say it's a backend app, like an express app, it will not be run on browser, rather it will be started from node itself. So, you set the target to be node. Which uses Node.js require to load chunks and not touch any built in modules like fs or path.

Refer here for more options. Also compare-webpack-target-bundles A great resource for testing and viewing different webpack targets. Also great for bug reporting.

Upvotes: 11

Related Questions