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-pratikkataria
folder which is insidedist-remote
that is at the same level aspackage.json
file. - 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
.cache
andpublic
(dist) folder - Run
gatsby build
- Removes content of
dist-remote/gatsby-pratikkataria
folder (Note:rimraf
does 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-origin
which 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)
DEPLOYPATH
that is a folder in your publicly available path, (2)REPOPATH
that points to remote-origin folder. - Remove contents of deploy folder
- Run
rsync
to copy over contents of repository folder to deploy folder - Give appropriate permissions to contents of
DEPLOYPATH
and remove all files/folders generated bygatsby build
from publicly available folder (~/public_html/
) - Copy over contents of
DEPLOYPATH
to publicly available folder
Voila! You’ve made a clean and easy deployment of your react/gatsby build onto your Shared Hosting server