【问题标题】:How can I tell Google closure compiler to not remove a var如何告诉 Google 闭包编译器不要删除 var
【发布时间】:2016-01-08 01:13:16
【问题描述】:

我有以下代码:

// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==

var l = window.location;
var s = 'hash';
l[s] = 'whatever i need now';

使用谷歌闭包编译器(高级模式)编译如下:

window.location.hash="whatever i need now";

但在这种情况下,我真的需要它在编译后的代码中继续使用l[s]= ...

有没有办法告诉编译器继续使用 var 或忽略几行?

Compiler in action - demo

【问题讨论】:

  • 我很好奇你为什么需要它。如果用在别处,应该保留,不是吗?
  • 为什么您需要保留l[s]= 部分?如果我们知道原因,我们或许可以提供帮助。
  • @yeouuu:嗯?您将不得不解释(可能带有引用),您的原始代码和 CC 的输出完全做同样的事情。 (另外:hash 不是一个函数,它是一个属性。)不,这不是无关紧要的。
  • 优化其余代码,将这三行保存在不同的文件中,然后将两者连接起来? .......我的想法已经用完了
  • 高级模式肯定不是实验性的。它有着悠久的稳定历史。

标签: javascript google-closure-compiler


【解决方案1】:

让哈希函数与 junos pulse 正常工作是一个小技巧。

我很难相信黑客是必要的,但是:

// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==

eval(
"var l = window.location;\n" +
"var s = 'hash';\n" +
"l[s] = 'whatever i need now';\n"
);

*hack* *咳嗽* :-)

或者:

// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==

sessionStorage.x = "hash";
window.location[sessionStorage.x] = 'whatever i need now';

【讨论】:

  • 哇,真够脏的,恭喜你使用 eval :)
  • @JeremyThille:我说,当黑客攻击时,想想eval。 ;-)
  • @yeouuu:是的。它保留了变量,这就是你所说的你需要的。
  • 哦,我会使用第二种方式。谢谢。
  • 我正在研究一个 github fork 来解释原因。当我准备好时,我会发布一个链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-09
相关资源
最近更新 更多