Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to uglify JavaScript using UglifyJS 2?

I tried to uglify a simple javascript file using UglifyJS2.

Here are the contents of the file :

//this is simply a sample var
var sampleVar = "xyz";

//lots of comments
//this is just another comment
//such things should not be present in javascript
//waiting to see result after uglifying

//this is simply a sample function
function sampleFunction()
{
  var sampleLocalVar = "xzx";
  if(true)
  {
    //inserting some sample comments
    alert("in if block");
  }
  else
  {
    //inserting some sample comments
    alert("in else block");
  }
}

Here's the command that I'm using to uglify:

uglifyjs -c -m sample.js sample.min.js

Error that I'm receiving :

Dot
Error parsing arguments in : sample.js
like image 366
Kazekage Gaara Avatar asked Dec 18 '13 08:12

Kazekage Gaara


2 Answers

You need to specify the output argument (-o or --output), as the documentation says:

Specify --output (-o) to declare the output file. Otherwise the output goes to STDOUT.

Also, the file to minify (or files to be concatenate and minify) must be specified first, as shown in the usage:

uglifyjs [input files] [options]

What you should be doing is the following:

uglifyjs sample.js -c -m -o sample.min.js

For more information about using UglifyJS2 from the command line, see the documentation.

like image 115
Qantas 94 Heavy Avatar answered Sep 18 '22 04:09

Qantas 94 Heavy


2 problems:

Firstly, the command line uglifyjs's argument parsing has a bug, so you have to either put the options at the end, or use -- to separate them from the command. For example:

uglifyjs -c -m foo.js     # Will fail Error parsing arguments in : foo.js 
uglifyjs foo.js -c -m     # Will work, printing the compressed
uglifyjs -c -m -- foo.js  # Will also work

Secondly, output goes to standard out by default. Passing more js files as parameters will concatenate them before minifiying. You can use -o to specify the output file, or use normal shell redirection operators (>, >>, | etc.)

uglifyjs -c -m -- foo.js                # Will output the file to stdout
uglifyjs -c -m -- foo.js > foo.min.js   # Will save the file to foo.min.js
uglifyjs -c -m  -o foo.min.js -- foo.js # Will save the file to foo.min.js
uglifyjs -c -m -- foo.js bar.js         # Will concatenate 2 js files
like image 39
rjmunro Avatar answered Sep 20 '22 04:09

rjmunro