How to prevent Closure Compiler from renaming “true”, “false” and “null”

…衆ロ難τιáo~ 提交于 2019-12-04 23:33:13

问题


Google Closure Compiler renames all "true", "false" and "null" occurences in code like;

var s = true, x = null, V = false;

and uses these shorthands instead; in conditions such as;

if (someVariable == s)

now; Google Analytics code defines it's own "s" variable; overriding the value "true"; and as you can see this causes a lot of problems.

I don't want to change GA code; I just want Closure Compiler to quit renaming true etc. Externs do not work.

Do you know any way to accomplish this?


回答1:


It turns out that one can prevent Google Closure Compiler from printing out global definitions (function and/or variable) by a parameter called "output_wrapper" to the command line code such as;

java -jar compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --output_wrapper "(function(){%output%})();" --js input.js --js_output_file output.js

This way, it doesn't collide with global variables and prints all your code in an anonymous function wrapper.




回答2:


Your main problem here is that your code runs in the global scope/namespace, that's why things crash.

To fix it, put it inside an anonymous function wrapper:

(function() {
    // a self contained "namespace"
    var s = true; // won't be affected by the analytics code anymore       


    // expose something
    window.foo = function() {};

})(); // execute the function immediately

This is the common idiom to prevent clashes of variable names etc. If you need to make things available outside of the wrapper, simply add them as properties to the window object.

Don't bother to mess with closure, when you change your code it might end up giving the variables different names. Also what when there are all of a sudden more global variables on your page? All those problems are good reasons to always put your code in a wrapper like the above.




回答3:


There is an option in CompilerOptions called aliasKeywords. When set to false, compiler will not alias 'true', 'false' and 'null'.



来源:https://stackoverflow.com/questions/4618571/how-to-prevent-closure-compiler-from-renaming-true-false-and-null

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