admin管理员组文章数量:1289529
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 acplish this?
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 acplish this?
Share Improve this question asked Jan 6, 2011 at 18:51 dasherswdashersw 2071 silver badge10 bronze badges 1-
Can you provide your own constants eg
_true_=true
and then replace with these before running though Closure Compiler? – El Ronnoco Commented Jan 6, 2011 at 19:01
3 Answers
Reset to default 11It 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 mand line code such as;
java -jar piler.jar --pilation_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.
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 mon 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.
There is an option in CompilerOptions
called aliasKeywords. When set to false
, piler will not alias 'true', 'false' and 'null'.
本文标签:
版权声明:本文标题:javascript - How to prevent Closure Compiler from renaming "true", "false" and "nul 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741406907a2376999.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论