SHARE
If you’re a video person then go ahead and watch the video uploaded on my YouTube Channel
First up let’s have a look at NPM scripts that’ll be needed. (Note: I am using a Gatsby project as an example)
1{
2 "scripts": {
3 "build": "rimraf .cache && rimraf public && gatsby build",
4 "deploy": "rimraf dist-remote/gatsby-pratikkataria/* && cpx \"public/**/*.*\" dist-remote/gatsby-pratikkataria && cd dist-remote/gatsby-pratikkataria && git add . && git commit -m \"Update\" && git push -u origin master"
5 },
6}
Before we go through the deploy script, there are few things I need you to know:
- I’ve a git repository setup on
gatsby-pratikkatariafolder which is insidedist-remotethat is at the same level aspackage.jsonfile. - This repository’s remote origin is in my CPanel under the path ->
~/repositories/gatsby-pratikkataria/
Now whenever I execute npm run build && npm run deploy it does the following:
- Removes
.cacheandpublic(dist) folder - Run
gatsby build - Removes content of
dist-remote/gatsby-pratikkatariafolder (Note:rimrafdoes not remove hidden files) - Copy over the new build files from
public(dist) folder todist-remote/gatsby-pratikkataria - Make a generic git commit and push to my
remote-originwhich resides on my CPanel.
Now the next part is convenient for me as it’s handled by my CPanel script that my Shared Hosting allows. If yours does not, you can just make a shell script which executes after getting new changes on remote-origin i.e. repository folder on your CPanel.
Let’s see the content of my CPanel script which exists in path dist-remote/gatsby-pratikkataria/.cpanel.yml (Note: being a hidden file, it’s not removed when I use rimraf)
1---
2deployment:
3 tasks:
4 - export DEPLOYPATH=/home/pratikka/public_html/gatsby-pratikkataria
5 - export REPOPATH=/home/pratikka/repositories/gatsby-pratikkataria
6 - rm -rf $DEPLOYPATH/*
7 - /bin/rsync -av --exclude=".*" $REPOPATH/ $DEPLOYPATH
8 - cd $DEPLOYPATH && chmod -R 755 . && cd ~/public_html/ && /usr/bin/find . -maxdepth 1 -regextype posix-egrep -regex ".\/(404|icons|offline-plugin-app-shell-fallback|page-data|static|workbox-v.+?|.+?.js|.+?.js.map|.+?.css|webpack.stats.json|chunk-map.json|manifest.webmanifest|.+?.html)" -exec rm -r {} +
9 - /bin/rsync -av --exclude=".*" $DEPLOYPATH/ ~/public_html
10
Now what exactly this is doing? Let’s go point-wise:
- Temporarily set 2 environment variables for convenience: (1)
DEPLOYPATHthat is a folder in your publicly available path, (2)REPOPATHthat points to remote-origin folder. - Remove contents of deploy folder
- Run
rsyncto copy over contents of repository folder to deploy folder - Give appropriate permissions to contents of
DEPLOYPATHand remove all files/folders generated bygatsby buildfrom publicly available folder (~/public_html/) - Copy over contents of
DEPLOYPATHto publicly available folder
Voila! You’ve made a clean and easy deployment of your react/gatsby build onto your Shared Hosting server

