Bootstrap

在Github Pages上部署SPA项目

步骤

1. 编写你的SPA项目

2. 修改打包工具的配置文件。这里使用Vite进行打包

export default defineConfig({
  base: '/[你的仓库名]/',
  build: {
    outDir: 'docs'
  }
})

3. 打包生成docs文件夹

4. 在docs的根目录下添加404.html(注意,如果你不打算使用github-pages的自定义域名的话,请将404.html中的pathSegmentsToKeep的值改为1)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Single Page Apps for GitHub Pages</title>
    <script type="text/javascript">
      var pathSegmentsToKeep = 0;
      var l = window.location;
      l.replace(
        l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
        l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
        l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
        (l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
        l.hash
      );
    </script>
  </head>
  <body>
  </body>
</html>

5. 在docs根目录下的index.html文件中添加如下内容

<script>
    (function (l) {
        if (l.search[1] === '/') {
            var decoded = l.search.slice(1).split('&').map(function (s) {
              return s.replace(/~and~/g, '&')
            }).join('?');
            window.history.replaceState(null, null,
              l.pathname.slice(0, -1) + decoded + l.hash
            );
        }
    }(window.location))
</script>

6. 将项目上传至github中(连同打包生成的docs目录一起上传。或者单独上传docs目录至仓库的gh-pages分支)。在仓库设置界面中配置github-pages

然后稍等片刻就可以访问了

注意

1. history路由模式可能会出现错误

2. 如果未能成功,建议观看下方的参考原文

参考

spa-github-pages
 

;