如何防止闭包编译器重命名“true”、“false”和“空”
Google Closure Compiler 重命名代码中所有出现的“true”、“false”和“null”,例如:
var s = true, x = null, V = false;
并使用这些简写来代替;在以下情况下;
if (someVariable == s)
现在; Google Analytics 代码定义了它自己的“s”变量;覆盖值“true”;正如你所看到的,这会导致很多问题。
我不想更改 GA 代码;我只是希望闭包编译器停止重命名 true 等。外部程序不起作用。
你知道有什么方法可以实现这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里的主要问题是您的代码在全局范围/命名空间中运行,这就是事情崩溃的原因。
要修复它,请将其放入匿名函数包装器中:
这是防止变量名称冲突等的常见习惯用法。如果您需要使某些内容在包装器之外可用,只需将它们作为属性添加到
window
对象即可。不要费心去搞乱闭包,当你更改代码时,它可能最终会给变量赋予不同的名称。另外,当页面上突然出现更多全局变量时该怎么办?所有这些问题都是始终将代码放入如上所述的包装器中的充分理由。
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:
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.
CompilerOptions
中有一个名为 别名关键字。当设置为false
时,编译器不会为“true”、“false”和“null”添加别名。There is an option in
CompilerOptions
called aliasKeywords. When set tofalse
, compiler will not alias 'true', 'false' and 'null'.事实证明,可以通过命令行代码中名为“output_wrapper”的参数来阻止 Google Closure Compiler 打印全局定义(函数和/或变量),例如;
这样,它就不会与全局变量发生冲突,并在匿名函数包装器中打印所有代码。
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;
This way, it doesn't collide with global variables and prints all your code in an anonymous function wrapper.