ClosureCompiler removing dead code with advanced optimizations

為{幸葍}努か 提交于 2019-12-11 12:06:38

问题


The following code:

(function() {
 var hello = function(name) {
  alert('Hello, ' + name);
 }
 hello('New user');
})();

with ADVANCED_OPTIMIZATIONS is compiled to:

alert("Hello, New user");

But this code:

(function() {
 var hello = function(name) {
  alert('Hello, ' + name);
 }
 hello.a = 5;
 hello('New user');
})();

is compiled to:

function a(b){alert("Hello, "+b)}a.a=5;a("New user");

Why it cannot ignore the hello.a = 5?

(It cannot be used outside the context, there is no eval, no [] and no new Function().)


回答1:


For this to work, the compiler would need to determine that no one had replaced "alert" with a function that looked at the the calling function:

alert = function() {
  console.log(arguments.callee.caller.a);
}

but "alert" is a external function so there is no way to determine what it actually does. Generally, javascript is so mutable that the cases where properties can be safely removed from functions are so rare it isn't worth the effort to find them.

Generally, where the Closure Compiler can remove properties it is cheating. There is some discussion of this here:

https://github.com/google/closure-compiler/wiki/Understanding-Property-Removal




回答2:


You can help the compiler optimize these by writing wrappers around the builtin functions:

function myalert(name){alert('Hello, ' + name)}
(function() {
 var hello = function(name) {
  myalert(name);
 }
 hello.a = 5;
 hello('New user');
})();

Produces:

alert("Hello, New user");

This can also be useful when you wrap commonly used things like document.createElement() for obfuscation and to an extent minification (when uncompressed).



来源:https://stackoverflow.com/questions/16546577/closurecompiler-removing-dead-code-with-advanced-optimizations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!