Running NPM on Forge when needed
When you add a new site in Forge the deploy script will be some like:
cd /home/forge/sample.comgit 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/fpmlockif [ -f artisan ]; then $FORGE_PHP artisan migrate --forcefi
To make add checks to run the NPM, you need to add the following code after the one above:
cd $FORGE_SITE_PATHtouch hash_resources.txtHASH_RESOURCES="$(cat hash_resources.txt)"find ./resources -type f -print0 | sort -z | xargs -0 sha1sum | sha1sum > hash_resources.txtHASH_NEW_RESOURCES="$(cat hash_resources.txt)"if [ "$HASH_RESOURCES" != "$HASH_NEW_RESOURCES" ]; then echo "Running: npm" npm install npm run prod rm -rf node_moduleselse 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 prodelse 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