As an old saying goes, “To do a good job, you must sharpen your tools.” As a front-end development, building a convenient development environment will bring great efficiency for our development work. While Webpack is an essential tool for front-end engineering packaging today, many people are not aware of the DevServer functionality that has been available since Webpack 4.

Let’s learn together!

1 What is webpack-dev-server

DevServer is an experimental feature of Webpack 3, which provides a hot update development server using the Webpack-dev-Middleware middleware. DevServer is designed to help developers quickly set up environments during development.

The latest Webpack 5 also supports reverse proxy, firewall, Socket, gZIP compression and other features.

2 Reverse proxy configuration

Similar to Nginx, webpack-dev-server implements URL proxy configuration through URL regular matching. The following codes are commonly used for configuration:

{
  "/rest/": {
    "target": "http://127.0.0.1:8080"."secure": false}}Copy the code

You can also proxy multiple entries to the same target by defining this configuration in JavaScript. Set the proxy configuration file to proxy.conf.js (instead of proxy.conf.json) and specify the configuration file as shown in the following example.

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

2.1 Basic Configuration Items

  • proxy:devServerProxy configuration
  • /api: indicates the request URL for which the proxy is required
  • target: Indicates the address of the reverse proxy
  • pathRewrite: Request address rewrite, similarNginxtheRewitefunction

Other writing methods refer to:

"pathRewrite": {
  "^/old/api""/new/api"
}

 // remove path
pathRewrite: {
  '^/remove/api'' '
}

// add base path
pathRewrite: {
  '^ /': '/basepath/'
}

// custom rewriting
pathRewritefunction (path, req{
  return path.replace('/api'.'/base/api');
}

// custom rewriting, returning Promise
pathRewriteasync function (path, req{
  const should_add_something = await httpRequestToDecideSomething(path);
  if (should_add_something) path += 'something';
  return path;
}
Copy the code

2.2 Other Configuration References

  • logLevel: Log printing level supported['debug', 'info', 'warn', 'error', 'silent'].silentDo not Print logs
  • logProvider: Custom log printing middleware
  • secure: Close or nothttpsSafety certification
  • changeOrigin: Modifies the proxy requesthost
  • protocolRewrite: Protocol rewrite,httpwithhttpsRequest transfers
  • cookieDomainRewrite: modifycookieDomainThe value of the
  • headers: Adds headers configuration to all requests
  • proxyTimeout: Request timeout period

2.3 Advanced Proxy Mechanism

  • OnError: Processing the request status code
function onError(err, req, res, target{
    res.writeHead(500, {
        'Content-Type''text/plain'}); res.end('Something went wrong. And we are reporting a custom error message.');
}
Copy the code
  • OnProxyRes: for the proxy interfaceResponseProcessing, which is used here to fetchcookie, redirection, etc
function onProxyRes(proxyRes, req, res{
    proxyRes.headers['x-added'] = 'foobar'// Add a header
    delete proxyRes.headers['x-removed']; // Delete a header
}
Copy the code
  • OnProxyReq: pairs the proxy interfacerequestUsed to set up before a requestcookie,headerOperations such as
function onProxyReq(proxyReq, req, res{
    // add custom header to request
    proxyReq.setHeader('x-added'.'foobar');
    // or log the req
}
Copy the code

3 Configure the domain name whitelist

After this configuration, only the matching host address can access the service. This configuration is used to simulate the network during the development phase. Network firewalls restrict access IP addresses. When the configuration item is set to all, the host check is skipped, but this is not recommended because of the risk of DNS attacks.

  1. Webpack configuration item configuration
module.exports = {
  / /...
  devServer: {
    allowedHosts: [
      'host.com'.'subdomain.host.com'.'subdomain2.host.com'.'host2.com',].}};Copy the code
  1. Cli startup command configuration
npx webpack serve --allowed-hosts .host.com --allowed-hosts host2.com
Copy the code

4 Port Configuration

  1. Webpack configuration item configuration
module.exports = {
  / /...
  devServer: {
    port8080,}};Copy the code
  1. Cli startup command configuration
   npx webpack serve --port 8080
Copy the code

Angular Uses the WebPack devServer proxy REST interface to the local server

In the Angular framework, proxy configuration files default to proxy.config.json because webPack is wrapped. (The js configuration file needs to be modified in the angular.json configuration file.) The following uses proxy.config.json as an example.

  1. Proxy all interfaces starting with /rest/ to 127.0.0.1:8080 and change the /rest/ request address to /
{
  "/rest/": {
    "target""http://127.0.0.1:8080"."secure"false."pathRewrite": {
      "/rest/""/"
    },
    "changeOrigin"true."logLevel""debug"."proxyTimeout"3000}}Copy the code

Access the boot address test {{host address}}/rest/testApi

  1. Add CFTK headers to all/REST/interfaces

Change the proxyConfig in angular.json to proxy.config.js and add the following content to proxy.config.js:

const PROXY_CONFIG = [
    {
        "target""http://127.0.0.1:8080"."secure"false."pathRewrite": {
            "/rest/""/"
        },
        "changeOrigin"true."logLevel""debug"."proxyTimeout"3000."onProxyReq"(request, req, res) = > {
            request.setHeader('cftk'.'my cftk'); }},];module.exports = PROXY_CONFIG;
Copy the code

6 Webpack-dev-server vs. Nginx

       webpack-dev-server    nginx
Usage scenarios Local development The whole scene
Network support  https/http/http2/ws  HTTP/HTTPS/http2 / ws/FTP, etc
Loading way The compiled code is loaded into memory for better performance. Hot updates can be carried out with Webpack. When the project is large, it takes up too much memory Read the contents of the hard drive, suitable for large projects
Gzip support support support
thread Single thread multithreading
Forward agent Does not support support
The reverse proxy support Support, more powerful functions
Service support A single point of support Supports multiple services and load balancing
To fit the difficulty  易   难 
conclusion It is very suitable for local development mode, in which the code is read into memory, better performance, reduce the compilation time after each change, simple learning cost is low, in some authentication scenarios do not need other third-party plug-ins can obtain cookies and other information, more friendly to developers. However, due to compilation and proxy binding, the cost of each configuration change is large Decathlon is an excellent server with very powerful functions, but the configuration is also complicated, and there is a certain learning cost. Local joint investigation requires browser plug-ins to obtain browser information such as cookies, and the maintenance of configuration files involves the communication cost of the team