如何在GitHub Action构建Flutter Web时自动移除或修改index.html中的base-href
解决GitHub Action自动构建Flutter Web时base href导致页面空白的问题
我帮你梳理两个更合理的自动化方案,完全不需要手动修改index.html就能解决页面空白的问题:
方案一:构建后自动替换base href(通用场景)
既然Flutter的--base-href参数强制要求首尾带/,我们可以在构建完成后,用Linux的sed命令直接修改生成的index.html文件,把默认的<base href="/">替换成<base href="./">。
只需要在你的GitHub Action配置里,在flutter build web步骤之后添加一个文本替换步骤即可:
# 原构建步骤 - run: flutter build web --release --web-renderer html # 新增:自动替换base href为相对路径 - run: sed -i 's|<base href="/">|<base href="./">|g' build/web/index.html
修改后的完整build_deploy.yaml配置如下:
name: Flutter Web on: push: branches: - master jobs: build: name: Build Web env: my_secret: ${{secrets.commit_secret}} runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: subosito/flutter-action@v1 with: channel: 'stable' - run: flutter config --enable-web - run: flutter clean - run: flutter pub get - run: flutter build web --release --web-renderer html # 自动替换base href为相对路径 - run: sed -i 's|<base href="/">|<base href="./">|g' build/web/index.html - run: | cd build/web git init git config --global user.email mymail@gmail.com git config --global user.name yeasin50 git status git remote add origin https://${{secrets.commit_secret}}@github.com/yeasin50/flavors_with_flutter.git git checkout -b gh-pages git add --all git commit -m "update" git push origin gh-pages -f
这个方案的好处是通用性强,不管你部署到子域名、子目录还是本地环境,相对路径./都能让资源正确加载。
方案二:使用符合要求的base-href参数(GitHub Pages专属场景)
如果你的Web应用固定部署到GitHub Pages的仓库子路径(比如你的仓库是flavors_with_flutter,访问地址是https://yeasin50.github.io/flavors_with_flutter/),那完全可以直接用Flutter官方支持的--base-href参数,设置为你的仓库路径:
run: flutter build web --release --web-renderer html --base-href /flavors_with_flutter/
这个参数完全符合Flutter的要求(首尾都是/),生成的index.html会自动带上<base href="/flavors_with_flutter/">,GitHub Pages加载资源时路径完全正确,不需要额外修改文件。
为什么不推荐用/./?
你之前尝试的--base-href /./虽然能绕过参数检查,但本质是个hack——浏览器解析/./时会等同于根路径/,实际并没有解决相对路径的问题,遇到子路径部署时还是可能出错,不如上面两种方案可靠。
内容的提问来源于stack exchange,提问作者Md. Yeasin Sheikh




