Deploying an 11ty Site to GitHub Pages Using GitHub Actions
The last time I wrote about deploying to GitHub Pages, it was essentially a tutorial on how to use Travis CI for deployment to GitHub Pages.
Travis, unfortunately, discontinued their free plan but GitHub Actions has become available and, for my needs, works just great. So, here’s how I set up my 11ty sites to deploy automatically to GitHub Pages.
Workflows
GitHub uses custom workflows to run tasks. There’s a marketplace on GitHub for various workflows and I used Eleventy Action for my needs.
It essentially does a build of the 11ty project and then uses the GitHub Pages action to deploy the _site
folder to the gh-pages
branch.
You save the Eleventy Action file to .github/workflows
folder in your codebase. When you push new code, this workflow will automatically run. You can see that the action runs from the Actions tab in your repository on GitHub.
Deployment
Now we need to deploy the gh-pages
branch to GitHub Pages. The easiest way to do that is under Settings > Pages. Under Build and deployment, set source to Deploy from a branch and specify the gh-pages
branch.
When you push updates to your repository, you should now see two workflows run under the Actions tab. The first is the Eleventy Build and the other is pages-build-deployment.
It is my understanding that you could set the source to GitHub Actions instead of gh-pages
and then add some additional incantations to the workflow file to do the same thing but I feel like setting it the way I’ve outlined here is the easiest. It feels unintuitive to me in that there are two workflows running but defined in two separate places.
Custom Domain
I have my sites use a custom domain and when you set the custom domain in Settings, it’ll create a CNAME file in the root of the gh-pages
branch. The problem is that the next time you do a push, the build will blow the file away and you’ll lose your custom domain name.
There are two ways to solve this problem.
The first is to specify the cname in the workflow file you created in your project earlier.
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
publish_dir: _site
publish_branch: gh-pages
github_token: ${{ secrets.GITHUB_TOKEN }}
cname: smacss.com
The second way is to add a new file in the root of your main repo that is called CNAME. Inside that file is a single line that has your domain name. (In my example, the file contents just say smacss.com
.)
Then, we need to tell Eleventy to pass that file through to the _site
folder. In the .eleventy.js
file, there’s likely a section already for passing through files. (If there’s not, just create a new one.)
module.exports = function(eleventyConfig) {
eleventyConfig.addPassthroughCopy("CNAME");
};
Finished
The GitHub Actions are still a little fuzzy for me. As such, I feel like I might’ve made this more complicated than it needs to be but for now, this is working.