Thursday, May 8, 2014

Minify JavaScript using UglifyJS and NodeJS

copyright from: freshbrewedcode.com
Minifying JavaScripts has many benefits. A few advantages are it reduces the amount of code the user has to download, removes unnecessary comments, and reduces the number of Http requests. There are many minify-ers out there, things such as YUI CompressorJSMinGoogle Closure Compiler, and UglifyJS.
I recently started using the standalone UglifyJS tool that can run in NodeJS. This makes the tool available via command prompt as well as accessing it inside of Node applications with require.
To use Uglify in Windows. First, download and install NodeJS. Once it is installed, you can then run applications in Command Prompt simply by typing node. It installs by default into C:\Program Files\NodeJS or C:\Program Files(x86)\NodeJS on a 64-bit machine.
It drops the node.exe, and the npm.bat file into that directory and makes it available in CMD by adding it to your %PATH%.
NPM is the Node Package Manager that was just recently made available for Windows. It allows you to download Node packages to be easily used in your projects.
The next step is to install UglifyJS and make it global so it’s available everywhere.
Open Command Prompt and run…
npm -g install uglify-js
This put’s the files for Uglify in the %AppData% file, usually around C:\Users\{username}\AppData\Roaming\npm\
As of 1/9/2012, there is a slight bug in the command to actually run Uglify, so in order to fix it, navigate to the folder just mentioned and find uglifyjs.cmd and replace it with…
:: Created by npm, please don't edit manually.
@IF EXIST "%~dp0"\"node.exe" (
  "%~dp0"\"node.exe"  "%~dp0\.\node_modules\uglify-js\bin\uglifyjs" %*
) ELSE (
  node  "%~dp0\.\node_modules\uglify-js\bin\uglifyjs" %*
)
Now, you will be able to just run Uglify by…
cd c:\place\where\files\are\
uglifyjs -o myFile.build.js myFile.js
And wham bam, you’ll find a nicely compressed file. NOTE: You also may need to restart the computer. Sometimes the changes to the path don’t kick in right away. You can string along as many files as you need to compress; the –o flag tells Uglify where to place the built file. Then you could save the commands out to some build.bat file and run it at your plessure.