free-tech

How to Deploy ReactJs app to GitHub Pages


GitHub  repository  content can be deployed in internet just by going to the settings of your repository and choosing from which branch you want the content of your future website to be served.
After choosing a branch its content will be deployed within a couple of minutes. the site is deployed under the URL which is comprised of your GitHub account name and repository name.

How to Deploy ReactJs app to GitHub Pages

the problem is we want the compiled code  served in a website, not just static content you have in your repository as sources.

So put it simply, if you’d just change the setting in the GitHub repository as described before, the code structure like in the pic below will just result in README.md shown on the website.

How to Deploy ReactJs app to GitHub Pages

Not really what we expected, huh? Let me show you how to solve this by example in React.

Example:

To deploy our test app, we need to change only one file: package.json

That’s why what I’ll describe further applies to basically any other JavaScript application, with minor differences in build script trigger.

First, we’d need a gh-pages dev dependency, let’s add it by running:
npm install gh-pages --save-dev

Second, let’s add our website URL to the top-level declaration in the package.json file, for example, I’d have it like this:
"homepage": "https://test.github.io/test"

Third and last step before deploying we need to declare deployment scripts in the scripts section of the package.json file:
"predeploy": "npm run build",
"deploy": "gh-pages -d build",

As of this moment, we are done with configuring, let’s run
npm run deploy

This command will do the following:

  1. run pre-deploy script building our application source code
  2. create a git branch with the name gh-pages if it didn’t exist before (like from previous executions of this command)
  3. push compiled code to this branch and serve it to the webpage under the URL we specified in the second step. Settings of the GitHub repository will change correspondingly, like serving from the gh-pages branch.
  4. The webpage will be live in a couple min