You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何强制rspack/rsbuild构建时使用相对路径?

解决RSBuild部署Github Pages时的相对路径问题

问题场景

用npm create rsbuild@latest基于rspack创建React应用,部署到Github Pages后页面空白,浏览器控制台提示静态资源加载失败。查看生成的HTML文件,发现所有静态资源(JS、CSS)的引用路径都是以/开头的绝对路径:

<!doctype html>
<html>
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script defer src="/static/js/lib-react.66d7bffd.js"></script><script defer src="/static/js/234.7da32f54.js"></script><script defer src="/static/js/index.0006388e.js"></script>
      <link href="/static/css/index.ff669eb5.css" rel="stylesheet">
   </head>
   <body>
      <div id="root"></div>
   </body>
</html>

手动给每个路径前添加.改为相对路径后,页面恢复正常,想知道如何让rspack/rsbuild默认生成相对路径。

解决步骤

  1. 在项目根目录找到rsbuild.config.js,若不存在则手动创建
  2. 在配置文件中添加output.publicPath配置,指定为相对路径:
export default {
  output: {
    publicPath: './',
  },
};
  1. 执行npm run build重新构建项目
  2. 将新生成的构建产物部署到Github Pages即可

内容的提问来源于stack exchange,提问作者baitendbidz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 00:50:02