20

I'm not that versed in unix and I cannot have Java, so YUI Compressor does not apply, but I have this known Minify tool, which will get a minified version of a JS/CSS file from a specific URI /min/?f=/path/to/file.js.css

Which unix commands may I use, using such method, to minify all the js/css files on the public_html folder, replacing all js/css files by their minified versions?

2

2 Answers 2

31

After searching and implementing it, I give the answer here through a bash file.

I use the npm packages uglifyjs and uglifycss for compressing JS and CSS files respectively. I use command find to loop through those files. I assume js and css files are in a js/ and a css/ folder respectively.

#minification of JS files
find js/ -type f \
    -name "*.js" ! -name "*.min.*" ! -name "vfs_fonts*" \
    -exec echo {} \; \
    -exec uglifyjs -o {}.min {} \;

#minification of CSS files
find css/ -type f \
    -name "*.css" ! -name "*.min.*" \
    -exec echo {} \; \
    -exec uglifycss --output {}.min {} \;

This will minify all js and css files in respective js/ and css/ directories. If you want to exclude some particular folders or patterns within them use the option ! -name


If you want to simply replace the minified file by the original file, that is, removing original file:

#minification of JS files
find js/ -type f \
    -name "*.js" ! -name "*.min.*" ! -name "vfs_fonts*" \
    -exec echo {} \; \
    -exec uglifyjs -o {}.min {} \; \
    -exec rm {} \; \
    -exec mv {}.min {} \;

#minification of CSS files
find css/ -type f \
    -name "*.css" ! -name "*.min.*" \
    -exec echo {} \; \
    -exec uglifycss --output {}.min {} \; \
    -exec rm {} \; \
    -exec mv {}.min {} \;
3
  • Is there a possibility to not rename but to have them like myScript.js and myScript.min.js ? Nov 16, 2018 at 8:43
  • 1
    @ChristopheFerreboeuf yes, remove the last two lines -exec rm {} \; and -exec mv {}.min {} \; Feb 4, 2019 at 13:17
  • npm minify doesn't have -o option that needs redirect >. How to make it work through changing -exec uglifyjs -o {}.min {} \; ?
    – caot
    Nov 29, 2020 at 23:16
6
sudo apt-get install yui-compressor
yui-compressor finename.css > filename.min.css

Sources :

3
  • I cannot use Yum Dec 24, 2017 at 13:17
  • I'm sorry ! I knew this is not the perfect solution, but I through it could help others. I hope that since December 2016 you found a solution !
    – FIfi
    Dec 24, 2017 at 13:45
  • 6
    This solution uses yui-compressor, which uses Java. The question stated I cannot have Java, so YUI Compressor does not apply
    – MichielB
    Mar 5, 2018 at 16:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .