Thursday, June 4, 2020

Deploy your React app to GitHub pages

Publish to Github

Simple and easy steps to publish your React app in GitHub pages.

Create a React App
Easily create a React application using 'create-react-app' CLI.

npm create-react-app my-app

Add a homepage key in your package.json file

"homepage": "https://<your_github_username>.github.io/<your_project_repository_name>/"

Change directory to 'my-app' and run the application.

cd my-app
yarn start
//or
npm start

Your sample app is ready to view.

Install tool to remove unnecessary files for 'gh-pages' branch.

yarn add -D gh-pages
// or
npm i -D gh-pages

Add a script for deployment in the scripts section of package.json file.

"scripts": {
  // ... Other scripts
  "deploy": "gh-pages -d build"
}

Build your app

To create a production build of your app, run the following command:

yarn build
// or
npm run build

A build folder will be created with optimized files, which we will deploy to gitHub pages.

Create a new repository on GitHub
You need to have GitBash installed.
In the root directory right click and select 'GitBash Here'.
Initialize the local directory as a Git repository.

git init

Add the files in your new local repository. 

git add .

Commit the files.

git commit -m '<commit message>' 

Copy the remote repository URl from GitHub.
Click on the 'Clone or download' button and copy the url.
Add the URL for the remote repository.

git remote add origin <remote repository URL>

Sets the new remote:

git remote -v

Push the changes in your local repository to GitHub.

git push origin master

Create a 'gh-pages' branch in your local repository.

git checkout -b gh-pages

Merge the master branch

git merge master

You will get a screen like this:


Press "i" key and insert your commit message.
Then press Esc key
Type ':wq' and press enter,
If there are no conflicts, your code will be merged.

Deployment
Publish your app using the deployment script

yarn deploy
// or
npm run deploy

View your application using the homepage value you defined earlier:
https://<your_github_username>.github.io/<your_project_repository_name>/

Congrats your app is up and running in GitHub pages. 😃