Boo-yah! Ever wondered how to deploy a react application on gh-pages?๐ค I learned 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 know 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 customized domain which will eventually redirect username.github.io to sitename.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 the gh-pages. ยฏ_( อกโ อส อกโ)_/ยฏ
The trick โจ
There are 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 the below line to the top of everything in the 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"
}
- Initialize an empty git repository even without README.md as it will be created already when youโll use create-react-app but not in the 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 โ๏ธ