最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why uglifyjs doesn't remove dead code? - Stack Overflow

programmeradmin3浏览0评论

For instance, I have the following code:

if ("a" !== "a") {
    console.log('really?');
}

var a = 5;

Then I write uglifyjs code.js -o code.min.js. As a result, I have the following:

if("a"!=="a"){console.log("really?")}var a=5;

How do I enable removing the dead code inside the if-statement?

For instance, I have the following code:

if ("a" !== "a") {
    console.log('really?');
}

var a = 5;

Then I write uglifyjs code.js -o code.min.js. As a result, I have the following:

if("a"!=="a"){console.log("really?")}var a=5;

How do I enable removing the dead code inside the if-statement?

Share Improve this question asked Aug 20, 2015 at 4:41 user2991036user2991036 4215 silver badges9 bronze badges 4
  • What's the dead code? console.log? or the entire if block? The former is a perfectly valid code with perfectly valid purpose. It is very different than optimizingif(a == 1 || a == 1). Plus I think uglifier does very limited optimization. – CppLearner Commented Aug 20, 2015 at 4:48
  • The code inside the if-block will never run. So, it's dead. – user2991036 Commented Aug 20, 2015 at 4:49
  • you need static analysis tool, not just AST parser. – CppLearner Commented Aug 20, 2015 at 4:51
  • 1 @CppLearner, you surely need to know what you're disputing about. Stackoverflow is not the place where you express your thoughts or doubts and especially not the place where you convince others that you know what you actually don't know. UglifyJS2 does dead code removal just perfectly. – meandre Commented Nov 12, 2015 at 9:08
Add a comment  | 

2 Answers 2

Reset to default 16

Despite this question has already got an accepted answer, I think it's worth mentioning that

  1. UglifyJS2 does remove dead code

  2. To turn this feature on, you need to set appropriate option either in CLI (uglifyjs --compress unused,dead_code) or in the options object if you invoke uglify programmatically (uglify(compress: { unused: true, dead_code: true });).

As per the README for uglifyjs, the maintainer has shifted development effort to UglifyJS2. The README also says that it only removes:

some unreachable code and warn about it (code that follows a return, throw, break or continue statement, except function/variable declarations).

Uglify2 does a more comprehensive job. I tested your code on the demo site and it does indeed remove the whole if statement. It also supports 'conditional compilation' (or maybe more correctly conditional code removal) by allowing you to define globals at the command line when uglifying.

发布评论

评论列表(0)

  1. 暂无评论