Tech Note: A BBEdit Text Filter to Minify Javascript With Google Closure Compiler
BBEdit is the pinnacle of text editors for Mac OS; it is the El Supremo in the room at the top of the stairs. I’ve been using it on an almost daily basis for more years than I like to think about, and it just keeps getting better.
One of BBEdit’s great features: “Text Filters” that let you write a script or short program in almost any language, and have it work on the contents of the current text document. Today I searched in vain for an already-written text filter that would call the Google Closure Compiler to “minify” Javascript code, and ended up just writing one myself, and I’m passing it on in case someone else out there might find it useful.
To use this, you have to first install the Closure Compiler Java app on your system, which isn’t difficult:
- Download the ZIP file and expand it. (The decompression should happen automatically after downloading; if not, double click the ZIP file.)
- In the Finder’s Go menu, click “Go to Folder…” and enter
/usr/local/lib
in the dialog box. This opens a desktop window showing that folder. - Copy the file
compiler.jar
from the foldercompiler-latest
to this new window. Because it’s in a system directory, you’ll probably be asked to enter your login password before the copy will proceed.
That’s it — the Closure Compiler is ready to go. Unless you’ve removed it, Java is already installed in Mac OS, so you shouldn’t need to do anything else.
Now for the Text Filter. In BBEdit, open a new window and and enter this short and simple Bash shell script:
#!/bin/bash
echo -n $(java -jar /usr/local/lib/compiler.jar --compilation_level SIMPLE_OPTIMIZATIONS <&0)
This script needs to be placed in:
~/Library/Application Support/BBEdit/Text Filters
Easiest way to get it there is to first save it to the Desktop, as Closure compiler.sh
, then use the Finder’s Go->Go to Folder menu again to open the Text Filters folder, and move the file in. (This time, you shouldn’t need to enter a password because it’s your own Library folder.)
Now you’re ready to minify some Javascript. Open a BBEdit window with some code, then go to Text->Text Filters, and choose “Closure Compiler.” Wait a few seconds and BAM! All that code is suddenly compressed with the best minifier available. We’re talking maximum shrinkage here.
If you mark a selection before using the text filter, just that section will be minified. If you’re feeling adventurous, you can set the compilation_level option in the text filter to “ADVANCED_OPTIMIZATIONS,” but this won’t work with all code; there are some strict requirements. Check the Closure Compiler docs for more on that.