MauroBaptista.com

Running NPM on Forge when needed

Laravel Forge

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

1cd /home/forge/sample.com
2git pull origin master
3$FORGE_COMPOSER install --no-interaction --prefer-dist --optimize-autoloader
4 
5( flock -w 10 9 || exit 1
6 echo 'Restarting FPM...'; sudo -S service $FORGE_PHP_FPM reload ) 9>/tmp/fpmlock
7 
8if [ -f artisan ]; then
9 $FORGE_PHP artisan migrate --force
10fi

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

1cd $FORGE_SITE_PATH
2 
3touch hash_resources.txt
4 
5HASH_RESOURCES="$(cat hash_resources.txt)"
6 
7find ./resources -type f -print0 | sort -z | xargs -0 sha1sum | sha1sum > hash_resources.txt
8 
9HASH_NEW_RESOURCES="$(cat hash_resources.txt)"
10 
11if [ "$HASH_RESOURCES" != "$HASH_NEW_RESOURCES" ]; then
12 echo "Running: npm"
13 npm install
14 npm run prod
15 rm -rf node_modules
16else
17 echo "Skipped: npm run prod"
18fi

What is does

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

1touch hash_resources.txt

Get the current content of the hash file.

1HASH_RESOURCES="$(cat hash_resources.txt)"

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

1find ./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

1HASH_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.

1if [ "$HASH_RESOURCES" != "$HASH_NEW_RESOURCES" ]; then
2 echo "Running: npm"
3 npm install --production
4 npm run prod
5else
6 echo "Skipped: npm run prod"
7fi

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

1rm -rf node_modules

Note

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

1hash_resources.txt