GitHub React

Serving a Create React App Project via GitHub Pages

Being new to GitHub Pages, I experienced a couple of issues in the process of getting a Create React App project live.

Here’s how I got it working…

Problem 1

The first issue was the fact that you can’t point Pages to serve from a subdirectory (like /build) in your master branch, other than /docs. This post cleared up the fact that Pages only recognises the following options to serve your site from:

  1. master branch root (/)
  2. /docs directory on the master branch
  3. gh-pages branch

So that helped me identify the problem; I wanted to serve from my /build directory so the first two options weren’t going to work. It was going to be down to the third option.

The Solution

Assuming you’ve already run npm run build, you’ll want to push only your /build directory to a specific gh-pages branch on GitHub. To do that, first uncomment the directory in your .gitignore file and then run the following (solution found here):

git subtree push --prefix build origin gh-pages

That takes care of that problem…

Problem 2

Unfortunately, the solution above only gets us so far. To be precise, it points GitHub Pages at the /build directory.

However, if you navigate to the Pages URL for your repository you may be presented with a blank screen and some 404s in the console. Lovely!

The problem here is that our app is looking for its resources (files) in the wrong location.

// Looking here:

// ...should be looking here:

The Solution

To give our app a friendly nudge in the right direction, we need to make an edit to our package.json file in our project’s root directory. In the file, if you don’t have an entry for homepage already, add it in like so:

  "homepage": ".", // add this line here
  "name": "your-project-name",
  "version": "0.1.0",

As explained in the Create React App docs on Deployment, this will ensure that all asset paths are relative to the index.html file so we can run it from whichever location we want to.

Leave a Reply

Your email address will not be published.