Webpack.devServer 配置项如何使用?附devServer完整示例

发布时间 2023-11-19 12:48:14作者: azoux

前言: 我们在平常本地开发时,可能经常需要与后端进行联调,或者调用一些api,但是由于浏览器跨域的限制、开发与生产环境的差异、http与https等问题经常让联调的过程不够顺畅。所以本文介绍一下webpack的devServer中的proxy配置项。接下来让我们先看一下这个配置项的基本使用:


基本使用

  1. 基本代理配置:如果你有一个在localhost:3000上的后端,你可以通过简单的配置将/api路由代理到这个后端服务器。webpack会对所有本地发出的前缀为/api的请求,转发到localhost:3000
   proxy: {
     '/api': 'http://localhost:3000',
   }
  // 示例
  // 假设你本地的前端服务跑在8080端口
  axios.get('/api/user/info') // 会被转发到 -> localhost:3000/api/user/info
  axios.get('/user/info') // 不会被转发, localhost:8080/user/info
  1. 路径重写:如果你不希望在代理请求时传递原始路径(例如/api),可以使用pathRewrite来重写它。这里的^/api: ''的意思是匹配接口路径中的/api,并将其替换为空字符串
  • 在这个例子中,任何以 /api 开头的请求路径在转发之前都会将 /api 部分替换为空字符串。例如,如果你发起一个请求到 /api/users,那么实际发送到后端服务器的请求路径将是 /users。
  • ^:匹配字符串的开始部分。
  • target 是后端的地址
  • 最后的请求路径会是:http://localhost:3000/users
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        pathRewrite: { '^/api': '' },
      },
    }
    
  1. 处理HTTPS和无效证书:默认情况下,代理不会接受运行在HTTPS上且证书无效的后端服务器。要允许这样的配置,可以将secure选项设置为false

    proxy: {
      '/api': {
        target: 'https://other-server.example.com',
        secure: false,
      },
    }
    
  2. 条件代理:通过一个函数判断是否需要代理。例如,对于浏览器请求,你可能希望提供一个HTML页面,而对于API请求,则希望代理它。

    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';
          }
        },
      },
    }
    
  3. 多路径代理:如果你想将多个特定路径代理到同一个目标,可以使用具有context属性的对象数组。

    proxy: [
      {
        context: ['/auth', '/api'],
        target: 'http://localhost:3000',
      },
    ]
    
  4. 改变原始主机头:代理默认保持原始的主机头。如果需要,可以通过设置changeOrigintrue来改变这个行为。

    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
      },
    }
    

devServer配置示例

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    // 入口文件配置
    entry: './src/index.js',

    // 输出文件配置
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },

    // 开发服务器配置
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        compress: true,
        port: 9000,
        proxy: {
            // 配置代理规则 '/api'
            '/api': {
                target: 'http://localhost:3000', // 目标服务器地址
                pathRewrite: { '^/api': '' }, // 路径重写,将 '/api' 替换为 ''
                secure: false, // 如果是 https 接口,需要配置为 true
                changeOrigin: true // 需要虚拟托管站点
            },
            // 你可以在这里继续添加更多的代理规则
        }
    },

    // 插件配置
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        })
    ],

    // 模块配置
    module: {
        rules: [
            // 在这里添加 loader
        ]
    }
};

在这个配置中:

  1. entryoutput 分别配置了入口和输出文件。

  2. devServer 是开发服务器的配置:

    • contentBase 指定了静态文件的位置。
    • compress 开启 gzip 压缩。
    • port 设置开发服务器的端口为 9000。
  3. devServer.proxy 是重要的代理配置部分:

    • 针对任何以 /api 开始的请求,代理规则会将请求转发到 http://localhost:3000 上。
    • pathRewrite 将路径中的 /api 替换为空字符串,这意味着例如 /api/user 会被转发为 http://localhost:3000/user
    • secure: false 表示接受对 https 的代理,这在目标服务器使用自签名证书时很有用。
    • changeOrigin: true 用于控制 Host 头的值。如果为 trueHost 头会被修改为目标 URL 的主机名。
  4. pluginsmodule 分别用于配置 Webpack 插件和模块加载器。