Skip to content

Instantly share code, notes, and snippets.

@rguliev
Last active November 9, 2020 14:59
Show Gist options
  • Save rguliev/81b6b74ef921d8b03ea698556fceeedc to your computer and use it in GitHub Desktop.
Save rguliev/81b6b74ef921d8b03ea698556fceeedc to your computer and use it in GitHub Desktop.
A pre-commit hook to minify js & css files.
#!/bin/bash
# A pre-commit hook to update minified versions of
# css/js files on commit
# Go to the project's root
cd "$(dirname "$0")"
cd ../../
# Set up compression command
COMPRESSOR="./node_modules/uglify-js/bin/uglifyjs"
# Make sure compressor exists
if [[ ! -f $COMPRESSOR ]] ; then
echo 'ERROR: Compressor is not installed! Aborting...'
exit 1
fi
BRANCH=`git rev-parse --abbrev-ref HEAD`
if [ "$BRANCH" == 'master' ]
then
# For each css and js file
# If you want only certain files to be compressed
# Change it to: for fname in file1 file2 file3; do
# TODO: It would be more effective to update only changed files,
# i.e. take list of files from staging and minify them instead of all js/css files
find . -regextype posix-extended \
-iregex '.+\.(css|js)$' \
-not -iregex '.+\.min\.(css|js)' \
-not -path "*node_modules*" \
-print0 | while IFS= read -r -d $'\0' fname
do
echo "Minifying: $fname"
# Name of minified version: myscript.js -> myscript.min.js
minified_name="${fname%.*}.min.${fname##*.}"
# Minify the file
$COMPRESSOR --rename "$fname" > $minified_name
# Add the file to commit
git add $minified_name
done
fi
@rguliev
Copy link
Author

rguliev commented Nov 9, 2020

Then I doubt you should use this code:) But it is up to you of course. I do not know all the details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment