如何使用 UglifyJS 2 丑化 JavaScript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20653578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to uglify JavaScript using UglifyJS 2?
提问by Kazekage Gaara
I tried to uglify a simple javascript file using UglifyJS2.
我尝试使用UglifyJS2丑化一个简单的 javascript 文件。
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
回答by Qantas 94 Heavy
You need to specify the output argument (-o
or --output
), as the documentation says:
您需要指定输出参数(-o
或--output
),如文档所述:
Specify
--output
(-o
) to declare the output file. Otherwise the output goes to STDOUT.
指定
--output
(-o
) 以声明输出文件。否则输出到 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.
有关从命令行使用 UglifyJS2 的更多信息,请参阅文档。
回答by rjmunro
2 problems:
2 问题:
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的参数解析有一个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
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.)
其次,输出默认为标准输出。传递更多 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