Deploying Gatsby to GitHub.io
March 24, 2020
I just created this blog using Gatsby and deployed it to GitHub. If you want, you can see the source here.
The deployment however wasn’t very straight forward, especially when
deploying to a GitHub pages subdomain at github.io. I.e. username.github.io
.
This blog post is a reference for how you can deploy your Gatsby app to username.github.io
.
The docs are wrong.
My first attempt was to follow the Gatsby docs.
The docs tell you to simply add a package called gh-pages
, and then add a
new deploy script to your package.json
file.
The problem with doing this is that
it creates a new gh-pages branch and deploys there, and if you want to deploy to
username.github.io
, your built app needs to be on the master branch.
But your source code is in the master branch, and having your source and the built app all in the same place just becomes a mess!
The docs are correct.
The steps the Gatsby docs outline are actually right, we just need to add a couple
more steps at the end, so lets start by adding the gh-pages
package and deploy
script as outlined in the docs.
1. Install the gh-pages
package.
First, install the gh-pages
package, you can use either npm or yarn. Go to the
root level of your project directory, and on the command line type:
npm:
npm install gh-pages --save-dev
yarn:
yarn add gh-pages --dev
2. Add a deploy script.
In your package.json file, add the following script.
{
"scripts": {
"deploy": "gatsby build && gh-pages -d public -b master"
}
}
This is where the Gatsby docs stop, but there are a couple more steps required to cleanly get your app deployed.
3. Create a new branch for your source code
From inside your project directory, on the command line, type:
git checkout -b master-source
git push --set-upstream origin master-source
This is the branch that is going to hold all your source code. From this branch, we can run our deploy script, and push the built version of our app to the master branch. All of your development and writing blog posts etc will be done on this branch.
The master
branch will contain the built version app, but you don’t need to
switch to the master
branch, because the deploy script will deploy to the master
branch for us. You can do this using npm or yarn:
Using npm:
npm run deploy
Using yarn:
yarn deploy
Conclusion
And there you have it! Your Gatsby app is now deployed to username.github.io
.
Special thanks to Olivia who had this solution on her blog, check it out here
Happy coding!