CC 4.0 许可证

本节内容源自以下链接的内容,并受 CC BY 4.0 许可证约束。

除非另有说明,否则以下内容可被视为基于原始内容进行修改和删除的结果。

DevServer

本页描述了影响@rspack/dev-server(简称:devServer)行为的选项,其基于webpack-dev-server@5,有助于快速应用程序开发。

  • 类型: object
提示

如果当前应用程序不依赖于@rspack/dev-server,则 devServer 配置将不起作用。

例如,Rspack CLI 默认依赖于@rspack/dev-server,因此 devServer 配置可以在 Rspack CLI 项目中使用。Rsbuild 已实现自己的开发服务器并提供单独的“server”配置,因此 devServer 配置不能在 Rsbuild 项目中使用。

devServer.allowedHosts

  • 类型: string | string[] | 'all' | 'auto'
  • 默认: 'auto'

此选项允许您允许访问开发服务器的服务。

rspack.config.js
module.exports = {
  //...
  devServer: {
    allowedHosts: [
      'host.com',
      'subdomain.host.com',
      'subdomain2.host.com',
      'host2.com',
    ],
  },
};

模仿 Django 的ALLOWED_HOSTS,以.开头的值可用作子域通配符。.host.com 将匹配host.comwww.host.com,以及host.com 的任何其他子域。

rspack.config.js
module.exports = {
  //...
  devServer: {
    // this achieves the same effect as the first example
    // with the bonus of not having to update your config
    // if new subdomains need to access the dev server
    allowedHosts: ['.host.com', 'host2.com'],
  },
};

设置为'all' 时,此选项会绕过主机检查。不建议这样做,因为不检查主机的应用程序容易受到 DNS 绑定攻击。

rspack.config.js
module.exports = {
  //...
  devServer: {
    allowedHosts: 'all',
  },
};

设置为'auto' 时,此选项始终允许localhosthostclient.webSocketURL.hostname

rspack.config.js
module.exports = {
  //...
  devServer: {
    allowedHosts: 'auto',
  },
};

devServer.client

  • 类型: object

logging

  • 类型: 'log' | 'info' | 'warn' | 'error' | 'none' | 'verbose'
  • 默认: 'info'

允许在浏览器中设置日志级别,例如,在重新加载之前、在错误之前或启用热模块替换时。

rspack.config.js
module.exports = {
  //...
  devServer: {
    client: {
      logging: 'info',
    },
  },
};

overlay

  • 类型: boolean | object
  • 默认: true

当有编译错误或警告时,在浏览器中显示全屏覆盖层。

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

您可以提供具有以下属性的对象来进行更细粒度的控制

属性 解释
errors 编译错误
runtimeErrors 未处理的运行时错误
warnings 编译警告

所有属性都是可选的,如果未提供,则默认为true

例如,要禁用编译警告,您可以提供以下配置

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

要根据抛出的错误进行过滤,您可以传递一个接受error参数并返回布尔值的函数。

例如,要忽略由AbortController.abort()抛出的错误

rspack.config.js
module.exports = {
  //...
  devServer: {
    client: {
      overlay: {
        runtimeErrors: error => {
          if (error instanceof DOMException && error.name === 'AbortError') {
            return false;
          }
          return true;
        },
      },
    },
  },
};
警告

在配置文件中,函数将无法访问在外部作用域中声明的变量。

进度

  • 类型: boolean
  • 默认: true

在浏览器中以百分比形式显示编译进度。

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

重新连接

  • 类型: boolean | number
  • 默认: true

告诉开发服务器尝试重新连接客户端的次数。当值为true时,将无限次尝试重新连接。

rspack.config.js
module.exports = {
  //...
  devServer: {
    client: {
      reconnect: true,
    },
  },
};

当设置为false时,将不会尝试重新连接。

rspack.config.js
module.exports = {
  //...
  devServer: {
    client: {
      reconnect: false,
    },
  },
};

您也可以指定客户端尝试重新连接的具体次数。

rspack.config.js
module.exports = {
  //...
  devServer: {
    client: {
      reconnect: 5,
    },
  },
};

WebSocket 传输

  • 类型: 'ws' | 'sockjs'
  • 默认值: ws

此选项允许我们选择当前的devServer传输模式,以便为每个客户端单独设置,或者提供自定义客户端实现。这允许指定浏览器或其他客户端如何与devServer通信。

提示

webSocketServer提供'ws''sockjs'是设置devServer.client.webSocketTransportdevServer.webSocketServer为给定值的一种简便方法。

rspack.config.js
module.exports = {
  //...
  devServer: {
    client: {
      webSocketTransport: 'ws',
    },
    webSocketServer: 'ws',
  },
};
提示

当提供自定义客户端和服务器实现时,请确保它们彼此兼容,以便成功地进行通信。

要创建自定义客户端实现,请创建一个扩展BaseClient的类。

使用指向CustomClient.js的路径,这是一个自定义 WebSocket 客户端实现,以及兼容的'ws'服务器

rspack.config.js
module.exports = {
  //...
  devServer: {
    client: {
      webSocketTransport: require.resolve('./CustomClient'),
    },
    webSocketServer: 'ws',
  },
};

使用自定义的兼容 WebSocket 客户端和服务器实现

rspack.config.js
module.exports = {
  //...
  devServer: {
    client: {
      webSocketTransport: require.resolve('./CustomClient'),
    },
    webSocketServer: require.resolve('./CustomServer'),
  },
};

WebSocket URL

  • 类型: string | object
  • 默认值: {}

此选项允许指定 WebSocket 服务器的 URL(当您代理开发服务器并且客户端脚本并不总是知道要连接到哪里时很有用)。

rspack.config.js
module.exports = {
  //...
  devServer: {
    client: {
      webSocketURL: 'ws://0.0.0.0:8080/ws',
    },
  },
};

您也可以指定包含以下属性的对象

  • hostname: 告诉连接到 devServer 的客户端使用提供的 hostname。
  • pathname: 告诉连接到 devServer 的客户端使用提供的路径进行连接。
  • password: 告诉连接到 devServer 的客户端使用提供的密码进行身份验证。
  • port: 告诉连接到 devServer 的客户端使用提供的端口。
  • protocol: 告诉连接到 devServer 的客户端使用提供的协议。
  • username: 告诉连接到 devServer 的客户端使用提供的用户名进行身份验证。
rspack.config.js
module.exports = {
  //...
  devServer: {
    client: {
      webSocketURL: {
        hostname: '0.0.0.0',
        pathname: '/ws',
        password: 'dev-server',
        port: 8080,
        protocol: 'ws',
        username: 'rspack',
      },
    },
  },
};
提示

要从浏览器获取protocol/hostname/port,请使用webSocketURL: 'auto://0.0.0.0:0/ws'

devServer.compress

  • 类型: boolean
  • 默认: true

启用为所有提供的内容开启gzip 压缩

rspack.config.js
module.exports = {
  //...
  devServer: {
    compress: true,
  },
};

devServer.devMiddleware

  • 类型: object
  • 默认值: {}

webpack-dev-middleware提供选项,用于处理 Rspack 资产。

rspack.config.js
module.exports = {
  devServer: {
    devMiddleware: {
      index: true,
      mimeTypes: { phtml: 'text/html' },
      publicPath: '/publicPathForDevServe',
      serverSideRender: true,
      writeToDisk: true,
    },
  },
};

devServer.headers

  • 类型: array | function | object
  • 默认值: undefined

在所有响应中添加标题

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

您也可以传递一个数组

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

您也可以传递一个函数

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

devServer.historyApiFallback

  • 类型: boolean | object
  • 默认值: false

当使用HTML5 历史记录 API时,index.html页面可能需要替代任何404响应。通过将devServer.historyApiFallback设置为true来启用它。

rspack.config.js
module.exports = {
  //...
  devServer: {
    historyApiFallback: true,
  },
};

通过提供一个对象,可以使用rewrites等选项进一步控制此行为。

rspack.config.js
module.exports = {
  //...
  devServer: {
    historyApiFallback: {
      rewrites: [
        { from: /^\/$/, to: '/views/landing.html' },
        { from: /^\/subpage/, to: '/views/subpage.html' },
        { from: /./, to: '/views/404.html' },
      ],
    },
  },
};

当在路径中使用点(在 Angular 中很常见)时,您可能需要使用disableDotRule

rspack.config.js
module.exports = {
  //...
  devServer: {
    historyApiFallback: {
      disableDotRule: true,
    },
  },
};

有关更多选项和信息,请参阅connect-history-api-fallback文档。

devServer.host

  • 类型: 'local-ip' | 'local-ipv4' | 'local-ipv6' | string
  • 默认值: 'local-ip'

指定要使用的主机。如果您希望服务器在外部可访问,请按如下方式指定:

rspack.config.js
module.exports = {
  //...
  devServer: {
    host: '0.0.0.0',
  },
};

local-ip

指定local-ip作为主机将尝试将主机选项解析为您的本地IPv4地址(如果可用)。如果IPv4不可用,它将尝试解析您的本地IPv6地址。

local-ipv4

指定local-ipv4作为主机将尝试将主机选项解析为您的本地IPv4地址。

local-ipv6

指定local-ipv6作为主机将尝试将主机选项解析为您的本地IPv6地址。

devServer.hot

  • 类型: boolean | 'only'
  • 默认: true

启用 Rspack 的热模块替换功能

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

要在构建失败的情况下,将页面刷新作为回退,启用热模块替换,请使用hot: 'only'

rspack.config.js
module.exports = {
  //...
  devServer: {
    hot: 'only',
  },
};

devServer.liveReload

  • 类型: boolean
  • 默认: true

默认情况下,开发服务器在检测到文件更改时将重新加载/刷新页面。devServer.hot选项必须禁用,或者devServer.watchFiles选项必须启用,才能使liveReload生效。通过将devServer.liveReload设置为false来禁用它。

rspack.config.js
module.exports = {
  //...
  devServer: {
    liveReload: false,
  },
};
提示

实时重新加载仅适用于与 Web 相关的目标,例如webwebworkerelectron-renderernode-webkit

devServer.onListening

  • 类型: function (devServer)

提供在@rspack/dev-server开始监听端口上的连接时执行自定义函数的能力。

rspack.config.js
module.exports = {
  //...
  devServer: {
    onListening: function (devServer) {
      if (!devServer) {
        throw new Error('@rspack/dev-server is not defined');
      }

      const port = devServer.server.address().port;
      console.log('Listening on port:', port);
    },
  },
};

devServer.open

  • 类型: boolean | string | object | [string, object]
  • 默认: true

告诉开发服务器在服务器启动后打开浏览器。将其设置为true以打开您的默认浏览器。

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

要在浏览器中打开指定的页面

rspack.config.js
module.exports = {
  //...
  devServer: {
    open: ['/my-page'],
  },
};

要在浏览器中打开多个指定的页面

rspack.config.js
module.exports = {
  //...
  devServer: {
    open: ['/my-page', '/another-page'],
  },
};

提供要使用的浏览器名称,而不是默认名称

rspack.config.js
module.exports = {
  //...
  devServer: {
    open: {
      app: {
        name: 'google-chrome',
      },
    },
  },
};

该对象接受所有open选项

rspack.config.js
module.exports = {
  //...
  devServer: {
    open: {
      target: ['first.html', 'https://127.0.0.1:8080/second.html'],
      app: {
        name: 'google-chrome',
        arguments: ['--incognito', '--new-window'],
      },
    },
  },
};
提示

浏览器应用程序名称与平台相关。不要在可重用的模块中对其进行硬编码。例如,'Chrome'在 macOS 上是'Google Chrome',在 Linux 上是'google-chrome',在 Windows 上是'chrome'

devServer.port

  • 类型: 'auto' | string | number
  • 默认值: []

指定要监听请求的端口号

rspack.config.js
module.exports = {
  //...
  devServer: {
    port: 8080,
  },
};

port选项不能为null或空字符串,要自动使用空闲端口,请使用port: 'auto'

rspack.config.js
module.exports = {
  //...
  devServer: {
    port: 'auto',
  },
};

devServer.proxy

  • 类型: [object, function]
提示

Rspack 中的@rspack/dev-server使用webpack-dev-server v5,并且devServer.proxy是数组类型。如果您使用的配置是 v4 版本中的对象类型,则需要首先根据webpack-dev-server/migration-v5.md迁移对其进行迁移。

当您拥有独立的 API 后端开发服务器并希望在同一域上发送 API 请求时,代理某些 URL 会很有用。

开发服务器使用功能强大的http-proxy-middleware包。查看其文档以了解更高级的用法。请注意,http-proxy-middleware的某些功能不需要target键,例如其router功能,但是您仍然需要在配置中包含一个target键,否则@rspack/dev-server将不会将其传递给http-proxy-middleware

对于在localhost:3000上运行的后端,您可以使用此方法启用代理

rspack.config.js
module.exports = {
  //...
  devServer: {
    proxy: [
      {
        context: ['/api'],
        target: 'https://127.0.0.1:3000',
      },
    ],
  },
};

现在,对/api/users的请求将代理到https://127.0.0.1:3000/api/users

如果您不希望传递/api,我们需要重写路径

rspack.config.js
module.exports = {
  //...
  devServer: {
    proxy: [
      {
        context: ['/api'],
        target: 'https://127.0.0.1:3000',
        pathRewrite: { '^/api': '' },
      },
    ],
  },
};

默认情况下,运行在 HTTPS 上且证书无效的后端服务器将不被接受。如果您希望这样做,请像这样修改您的配置

rspack.config.js
module.exports = {
  //...
  devServer: {
    proxy: [
      {
        context: ['/api'],
        target: 'https://127.0.0.1:3000',
        secure: false,
      },
    ],
  },
};

有时您不希望代理所有内容。可以根据函数的返回值绕过代理。

在函数中,您可以访问请求、响应和代理选项。

  • 返回nullundefined以继续使用代理处理请求。
  • 返回false以对请求生成 404 错误。
  • 返回要从中提供的路径,而不是继续代理请求。

例如,对于浏览器请求,您希望提供 HTML 页面,但是对于 API 请求,您希望代理它。您可以执行以下操作

rspack.config.js
module.exports = {
  //...
  devServer: {
    proxy: [
      {
        context: ['/api'],
        target: 'https://127.0.0.1:3000',
        bypass: function (req, res, proxyOptions) {
          if (req.headers.accept.indexOf('html') !== -1) {
            console.log('Skipping proxy for browser request.');
            return '/index.html';
          }
        },
      },
    ],
  },
};

如果您希望将多个特定路径代理到同一个目标,可以使用包含context属性的一个或多个对象的数组

rspack.config.js
module.exports = {
  //...
  devServer: {
    proxy: [
      {
        context: ['/auth', '/api'],
        target: 'https://127.0.0.1:3000',
      },
    ],
  },
};

请注意,默认情况下,对根目录的请求不会被代理。要启用根目录代理,应将devMiddleware.index选项指定为假值。

rspack.config.js
module.exports = {
  //...
  devServer: {
    devMiddleware: {
      index: false, // specify to enable root proxying
    },
    proxy: [
      {
        context: () => true,
        target: 'https://127.0.0.1:1234',
      },
    ],
  },
};

默认情况下,代理时会保留主机标头的来源,您可以将changeOrigin设置为true以覆盖此行为。这在某些情况下很有用,例如使用基于名称的虚拟托管站点

rspack.config.js
module.exports = {
  //...
  devServer: {
    proxy: [
      {
        context: ['/api'],
        target: 'https://127.0.0.1:3000',
        changeOrigin: true,
      },
    ],
  },
};

devServer.server

  • 类型: 'http' | 'https' | 'spdy' | string | object
  • 默认值: 'http'

允许设置服务器和选项(默认情况下为 'http')。

rspack.config.js
module.exports = {
  //...
  devServer: {
    server: 'http',
  },
};

通过自签名证书在HTTPS上提供服务

rspack.config.js
module.exports = {
  //...
  devServer: {
    server: 'https',
  },
};

使用自签名证书,通过spdyHTTP/2上提供服务

rspack.config.js
module.exports = {
  //...
  devServer: {
    server: 'spdy',
  },
};

使用对象语法提供您自己的证书

rspack.config.js
module.exports = {
  //...
  devServer: {
    server: {
      type: 'https',
      options: {
        ca: './path/to/server.pem',
        pfx: './path/to/server.pfx',
        key: './path/to/server.key',
        cert: './path/to/server.crt',
        passphrase: '@rspack/dev-server',
        requestCert: true,
      },
    },
  },
};

它还允许您设置额外的TLS 选项,例如minVersion,您可以直接传递相应文件的原始内容。

rspack.config.js
const fs = require('fs');
const path = require('path');

module.exports = {
  //...
  devServer: {
    server: {
      type: 'https',
      options: {
        minVersion: 'TLSv1.1',
        key: fs.readFileSync(path.join(__dirname, './server.key')),
        pfx: fs.readFileSync(path.join(__dirname, './server.pfx')),
        cert: fs.readFileSync(path.join(__dirname, './server.crt')),
        ca: fs.readFileSync(path.join(__dirname, './ca.pem')),
        passphrase: '@rspack/dev-server',
        requestCert: true,
      },
    },
  },
};

devServer.setupMiddlewares

  • 类型: function (middlewares, devServer)

提供执行自定义函数并应用自定义中间件的能力。

rspack.config.js
module.exports = {
  // ...
  devServer: {
    setupMiddlewares: (middlewares, devServer) => {
      if (!devServer) {
        throw new Error('@rspack/dev-server is not defined');
      }

      devServer.app.get('/setup-middleware/some/path', (_, response) => {
        response.send('setup-middlewares option GET');
      });

      // Use the `unshift` method if you want to run a middleware before all other middlewares
      // or when you are migrating from the `onBeforeSetupMiddleware` option
      middlewares.unshift({
        name: 'first-in-array',
        // `path` is optional
        path: '/foo/path',
        middleware: (req, res) => {
          res.send('Foo!');
        },
      });

      // Use the `push` method if you want to run a middleware after all other middlewares
      // or when you are migrating from the `onAfterSetupMiddleware` option
      middlewares.push({
        name: 'hello-world-test-one',
        // `path` is optional
        path: '/foo/bar',
        middleware: (req, res) => {
          res.send('Foo Bar!');
        },
      });

      middlewares.push((req, res) => {
        res.send('Hello World!');
      });

      return middlewares;
    },
  },
};

devServer.static

  • 类型: boolean | string | object | [string, object]

此选项允许配置从目录(默认情况下为 'public' 目录)提供静态文件的选项。要禁用它,请将其设置为false

rspack.config.js
module.exports = {
  //...
  devServer: {
    static: false,
  },
};

要监视单个目录

rspack.config.js
module.exports = {
  // ...
  devServer: {
    static: ['assets'],
  },
};

要监视多个静态目录

rspack.config.js
module.exports = {
  // ...
  devServer: {
    static: ['assets', 'css'],
  },
};

devServer.watchFiles

  • 类型: string | object | [string, object]

此选项允许您配置要监视文件更改的 glob/目录/文件列表。例如

rspack.config.js
module.exports = {
  //...
  devServer: {
    watchFiles: ['src/**/*.php', 'public/**/*'],
  },
};

可以配置用于监视文件的高级选项。有关可能的选项,请参见chokidar 文档。

rspack.config.js
module.exports = {
  //...
  devServer: {
    watchFiles: {
      paths: ['src/**/*.php', 'public/**/*'],
      options: {
        usePolling: false,
      },
    },
  },
};

devServer.webSocketServer

  • 类型: false | 'sockjs' | 'ws'

此选项允许我们选择当前的 WebSocket 服务器或提供自定义的 WebSocket 服务器实现。

当前默认模式为 'ws'。此模式使用ws 作为服务器,并在客户端使用原生 WebSocket。

rspack.config.js
module.exports = {
  //...
  devServer: {
    webSocketServer: 'ws',
  },
};