如何使用 UglifyJS 2 压缩 JavaScript 代码?

6

我尝试使用UglifyJS2压缩一个简单的javascript文件。

以下是该文件的内容:

//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");
  }
}

这是我使用的压缩命令:

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

我收到的错误是:
Dot
Error parsing arguments in : sample.js
2个回答

11

根据文档,您需要指定输出参数 (-o--output):

要声明输出文件,请使用--output (-o)。否则,输出将被写入标准输出 (STDOUT)。

另外,需要首先指定要缩小的文件(或要连接并缩小的文件),如用法所示:

uglifyjs [input files] [options]

你应该做的是以下内容:

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

欲了解如何从命令行使用UglifyJS2,请查看文档


2

2个问题:

首先,命令行工具uglifyjs的参数解析存在一个bug,因此你必须将选项放在最后,或使用--将其与命令分离。例如:

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

其次,默认情况下输出到标准输出。传递更多的js文件作为参数将在缩小之前将它们连接起来。您可以使用-o指定输出文件,或使用正常的shell重定向运算符(>>>|等)。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接