MauroBaptista.com

Running NPM on Forge when needed

March 07, 2022

When you add a new site in Forge the deploy script will be some like:

cd /home/forge/sample.com
git pull origin master
$FORGE_COMPOSER install --no-interaction --prefer-dist --optimize-autoloader

( flock -w 10 9 || exit 1
  echo 'Restarting FPM...'; sudo -S service $FORGE_PHP_FPM reload ) 9>/tmp/fpmlock

if [ -f artisan ]; then
  $FORGE_PHP artisan migrate --force
fi

To make add checks to run the NPM, you need to add the following code after the one above:

cd $FORGE_SITE_PATH

touch hash_resources.txt

HASH_RESOURCES="$(cat hash_resources.txt)"

find ./resources -type f -print0 | sort -z | xargs -0 sha1sum | sha1sum > hash_resources.txt

HASH_NEW_RESOURCES="$(cat hash_resources.txt)"

if [ "$HASH_RESOURCES" != "$HASH_NEW_RESOURCES" ]; then
  echo "Running: npm"
  npm install
  npm run prod
  rm -rf node_modules
else
  echo "Skipped: npm run prod"
fi

What is does

Create the file that will hold the hash if they do not exist.

touch hash_resources.txt

Get the current content of the hash file.

HASH_RESOURCES="$(cat hash_resources.txt)"

Get the hash of all the files inside the resources folder, and save it inside the hash file.

find ./resources -type f -print0 | sort -z | xargs -0 sha1sum | sha1sum > hash_resources.txt

Note that if you change only your webpack.mix.js (or any other file outside the above cited folder) you need to run it manually in your server

Get the new calculated hash

HASH_NEW_RESOURCES="$(cat hash_resources.txt)"

Then we compare the old hash with the new one. If a single char was changed in the files, it will be a different hash, and then the commands will run.

if [ "$HASH_RESOURCES" != "$HASH_NEW_RESOURCES" ]; then
  echo "Running: npm"
  npm install --production
  npm run prod
else
  echo "Skipped: npm run prod"
fi

We already built our javascript files, so let’s save some space in the servers:

rm -rf node_modules

Note

In your .gitignore you need to add the file created above:

hash_resources.txt

Mauro Baptista

Mauro Baptista

Building stuff with code and having fun in the way

© 2022, Built with Gatsby