webpack advanced application: devServer

Posted by konrados on Mon, 06 Dec 2021 05:51:43 +0100

In the development environment, we often need to start a web service to facilitate us to simulate a user to access our web service from the browser and read our packaged products to observe the performance of our code on the client. Webpack 5 has such a built-in function. We only need a simple configuration to turn it on. Before that, we need to install it

npm i -D webpack-dev-server

Foundation use:

webpack.config.js

const path = require('path');

module.exports = {
  //...
  devServer: {
    static: { // By default, the / dist directory is taken as the root directory of the web service
      directory: path.join(__dirname, 'public'),
    },
    compress: true, // You can select to enable the gzip compression function. It is enabled by default in the response header corresponding to the static resource request
    port: 9000, // Port number
  },
};

After the service (server) is started, a message is output before parsing the module list:

Here will give some basic information about the service startup location and content.

Add response header

Under the requirements of some scenarios, we need to add headers for all responses to enter flags for resource requests and responses, so as to take some security precautions or make requests after exceptions occur

Link tracking. For example:

webpack.config.js

module.exports = {
  //...
  devServer: {
    headers: {
      'X-Custom-Foo': 'bar',
    },
  },
};

You can also pass an array:

webpack.config.js

module.exports = {
  //...
  devServer: {
    headers: [
      {
        key: 'X-Custom',
        value: 'foo',
      },
      {
        key: 'Y-Custom',
        value: 'bar',
      },
    ],
  },
};

You can also pass a function:

module.exports = {
  //...
  devServer: {
    headers: () => {
      return { 'X-Bar': ['key1=value1', 'key2=value2'] };
    },
  },
};

hot

'only' boolean = true

webpack enabled Hot module replacement characteristic:

webpack.config.js

module.exports = {
  //...
  devServer: {
    hot: true,
  },
};

Tip

Starting with webpack-dev-server v4, devServer.hot is enabled by default. It will be applied automatically webpack.HotModuleReplacementPlugin

open

boolean string [string] object [object]

Tell dev server to open the browser after the server has started. Set it to true to open your default browser.

webpack.config.js

module.exports = {
  //...
  devServer: {
    open: true,
  },
};

Open proxy

When the backend is on localhost:3000 and the client is on localhost:9000, you can use it to enable proxy to solve cross domain problems:

webpack.config.js

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': 'http://localhost:3000',
    },
  },
};

The request for / API / users will now proxy the request to http://localhost:3000/api/users .

If you do not want to pass / api, you need to rewrite the path:

webpack.config.js

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        pathRewrite: { '^/api': '' },
      },
    },
  },
};

Do not proxy all content

You can bypass the proxy based on the return value of the function.

In this function, you can access request, response and proxy options.

  • Return null or undefined to continue processing the request using the proxy.
  • Returning false will generate 404 errors for the request.
  • Returns the path that provides the service instead of continuing the proxy request.

For example. For browser requests, you want to provide an HTML page, but for API requests, you want to proxy it. You can do the following:

webpack.config.js

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        bypass: function (req, res, proxyOptions) {
          if (req.headers.accept.indexOf('html') !== -1) {
            console.log('Skipping proxy for browser request.');
            return '/index.html';
          }
        },
      },
    },
  },
};

Proxy multiple specific paths to the same destination

You can use an array of one or more objects with the context attribute:

webpack.config.js

module.exports = {
  //...
  devServer: {
    proxy: [
      {
        context: ['/auth', '/api'],
        target: 'http://localhost:3000',
      },
    ],
  },
};

changeOrigin

By default, the source of the host header is retained when the agent is, and you can set changeOrigin to true to override this behavior. In some cases, such as using name-based virtual hosted sites , it's very useful.

webpack.config.js

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
      },
    },
  },
};

If set to true: the host in the send request header will be set to target

client

overlay

boolean = true object: { errors boolean = true, warnings boolean = true }

Displays a full screen overlay in the browser when a compilation error or warning occurs.

webpack.config.js

module.exports = {
  //...
  devServer: {
    client: {
      overlay: true,
    },
  },
};

If you only want to display an error message:

webpack.config.js

module.exports = {
  //...
  devServer: {
    client: {
      overlay: {
        errors: true,
        warnings: false,
      },
    },
  },
};

progress

boolean

Displays compilation progress as a percentage in the browser.

webpack.config.js

module.exports = {
  //...
  devServer: {
    client: {
      progress: true,
    },
  },
};

Topics: Front-end Webpack Proxy