Hosting a react application using GitHub pages 🚀

Parth Pandya
3 min readMay 13, 2021

--

Github-Pages + React

Boo-yah! Ever wondered how to deploy a react application on gh-pages?🤔 I learnt it today and I’ll share it here how one can do that 😁

What made me learn it?🤔

Portfolio site of mine is developed in react-js. For hosting your portfolio with <username>.github.io you have to enable gh-pages. But this is a react application and before this I didn’t knew we can even deploy a react-app using gh-pages so what I did? The traditional way we follow to deploy a react-app is using Netlify. So what I did is, I added a CNAME file to add a customised domain which will eventually redirect <username>.github.io to <site-name>.netlify.app . Although it is a great trick, but every time when you’ll use gh-pages after that, this redirect thing happens. As a result of which, no results will be fetched from found at requested URL rather than a pissing 404.

I needed a solution immediately as I generally use gh-pages to host readmes. The only solution I see was to remove the domain customisation and use <username>.github.io For this, I had to find a way where I can actually host my react application using gh-pages. ¯\_( ͡❛ ͜ʖ ͡❛)_/¯

The trick ✨

There are a very few steps involved to host your react-application using gh-pages. These are listed in the below bulletin.

  • Create a react-app using create-react-app or blazepack create my-app --template=react whatever you prefer. Test it locally and complete developing the app.
  • Now open package.json in an editor. And do as directed below 👇
Add below line to the top of everything in file//...
"homepage": "https://<username>.github.io/<repository_name>"
Add below things to the scripts in the file//..."scripts": {
//...
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
  • Initialise an empty git repository even without README.md as it will be created already when you’ll use create-react-app but not in case of blazepack .
  • Shortcut to perform the above steps in one go 👇
$ sed -i '5i\  "homepage": "https://<username>.github.io/<repository_name>",' ./package.json$ sed -i '15i\    "predeploy": "npm run build",' ./package.json$ sed -i '16i\    "deploy": "gh-pages -d build",' ./package.json
  • Final step to deal is to do npm install gh-pages --save-dev which will add gh-pages as a dev-dependency in your project.
  • All set 🤝 final steps, just a single command away. Just run npm run deploy from the root of the project directory. This will generate a production build of your project and will deploy react-app to gh-pages.

That was all about how to host up your react-app using gh-pages 🚀

Quick fun fact about Readme 😎

Ever seen a stubborn link with the repository name stuck at the top of README.md when hosted using gh-pages? Well, that link can be removed from there adding a _config.yml file.

Just add title : <title you want to display at Readme>

That’s it, we fixed it ✔️

--

--

Responses (1)