There is a plenty of tools out there for you to use to this purpose, probably the most popular right now is the excellent npm package gh-pages
. So this is not intended to be a production deploy strategy, but its very simple and cool to know (and could be useful in another contexts, who knows). For this post I'm considering an application created with CRA, but with a few modifications you can use with any application, i guess. Also worth to mention that im running this script on a Debian 10 (also tested on Ubuntu 18).
First of all, add a homepage
key on your package JSON with the target address of your app, so react will use this address as the base URL while compiling your app:
// package.json
{
...
"homepage": "https://yourusername.github.io/your-project/",
...
}
Now create a gh-pages
branch on your project and come back to your main
(former master
branch).
git checkout -b gh-pages && git checkout main
Finally, create an SH file on your project root with the following content (you can use any name, like deploy.sh
for example):
#!/usr/bin/env
# checkout to the gh-pages, reset
# and sync the branch with our main
# change here to master if you need
git checkout gh-pages
git reset --hard origin/main
# install dependencies and create
# the react app build
npm install
npm run build
# delete everything on the directory
# except the build folder
find * -maxdepth 0 -name 'build' -prune -o -exec rm -rf '{}' ';'
# move the build folder content
# to the repository root
mv ./build/* .
# deletes the git cache and push
# the new content to gh-pages
git rm -rf --cache .
git add .
git commit -m "deploy"
git push origin gh-pages --force
# go back to main (or master)
git checkout main
Pay attention on the main
branch references on the script and change them to master
if its your case, and dont forget to give execution permission to your script:
sudo chmod +x ./deploy.sh
And all done. If you run your shell script, your React App will be deployed to gh-pages
:
./deploy.sh
Cover image by Ali Abdul Rahman on Unsplash.
Thats all folks.
Top comments (4)
Hi Felippe,
Just to fix a little thing on "git branch -b gh-pages && git checkout main"
Instead of "branch" would be "checkout"
Great tutorial!
thanks Felipe! fixed
or use this library npmjs.com/package/gh-pages#command...
yes, its how the post starts: