My approach to this is a Github action that:
- checks out the
main
branch
- performs the minification/purging etc
- pushes the changes to a
gh-pages
branch
Then you just need to point Github Pages at the gh-pages
branch rather than the main
branch.
You'd need to choose appropriate CLI tools to perform the minifying/purging in the virtual machine that the action spins up. There are lots of options here. I'd suggest using packages that can be installed through node
so that you only have to install that on the VM. For example:
This is relatively straightforward with a Github action that looks a bit like this:
# A Github Action that minifies html/css/js and pushes it to a new branch
name: purge-and-minify
# Run on pushes to `main` branch
on:
push:
branches:
- 'main'
jobs:
checkout-minify-push:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
# Install CLI tools
- uses: actions/setup-node@v3
with:
node-version: '16'
- run: npm install -g terser
- run: npm install -g csso-cli
- run: npm install -g html-minifier
# Use CLI tools to minify, overwriting existing files
- run: for i in ./js/*.js; do terser $i --compress -o $i; done
- run: for i in ./css/*.css; do csso $i -o $i; done
- run: for i in ./html/*.html; do html-minifier [--your-options-here] $i -o $i; done
# Push changes to `gh-pages` branch
- run: |
git config user.name github-username
git config user.email [email protected]
git commit -am 'Automated minify of ${{ github.sha }}'
git push --force -u origin main:gh-pages
Here is a working example of a similar process in a Github project of mine.