Using UglifyJs2 to minify JavaScript
July 5, 2013
I have a javascript application that I want to protect a little from casual source inspection. I'm going to do this by running a command line to update my source file, compressing one javascript file each time I upload to the server.
There are probably better ways of doing this with regard to caching, but for my purposes a simple "compress this file into this one at upload" will suffice.
Dependencies - Node
UglifyJS2 requires node.js. To install, download node (I used 0.10.12) and uncompress.
In the top level directory, run
$ ./configure $ make $ sudo make install
At this point you should be able to run node from the command line:
$ node --version
v0.10.12
Install UglifyJS
You can now install UglifyJS using npm:
$ sudo npm install uglify-js -g npm http GET https://registry.npmjs.org/uglify-js npm http 304 https://registry.npmjs.org/uglify-js npm http GET https://registry.npmjs.org/async npm http GET https://registry.npmjs.org/source-map npm http GET https://registry.npmjs.org/optimist npm http 200 https://registry.npmjs.org/optimist npm http GET https://registry.npmjs.org/optimist/-/optimist-0.3.7.tgz npm http 200 https://registry.npmjs.org/source-map npm http GET https://registry.npmjs.org/source-map/-/source-map-0.1.25.tgz npm http 200 https://registry.npmjs.org/optimist/-/optimist-0.3.7.tgz npm http 200 https://registry.npmjs.org/source-map/-/source-map-0.1.25.tgz npm http 200 https://registry.npmjs.org/async npm http GET https://registry.npmjs.org/async/-/async-0.2.9.tgz npm http 200 https://registry.npmjs.org/async/-/async-0.2.9.tgz npm http GET https://registry.npmjs.org/wordwrap npm http GET https://registry.npmjs.org/amdefine npm http 200 https://registry.npmjs.org/wordwrap npm http GET https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz npm http 200 https://registry.npmjs.org/amdefine npm http GET https://registry.npmjs.org/amdefine/-/amdefine-0.0.5.tgz npm http 200 https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz npm http 200 https://registry.npmjs.org/amdefine/-/amdefine-0.0.5.tgz /usr/local/bin/uglifyjs -> /usr/local/lib/node_modules/uglify-js/bin/uglifyjs npm WARN package.json github-url-from-git@1.1.1 No repository field. npm WARN package.json assert-plus@0.1.2 No repository field. npm WARN package.json ctype@0.5.2 No repository field. uglify-js@2.3.6 /usr/local/lib/node_modules/uglify-js ├── async@0.2.9 ├── source-map@0.1.25 (amdefine@0.0.5) └── optimist@0.3.7 (wordwrap@0.0.2)
Usage
You can now run uglifyjs from the command line to process the appropriate file:
$ uglifyjs app.js --output app.ugly.js --mangle --compress