简体   繁体   English

如何指示Closure Compiler不要重命名/删除局部变量?

[英]How to instruct Closure Compiler not to rename/remove a local variable?

In the following code, I need the variable some_var not to be renamed or removed by Google's Closure Compiler. 在以下代码中,我不需要Google的Closure Compiler重命名或删除变量some_var

function scopedEval(code){
    var some_var = 'world' ;
    return eval('('+code+')') ;
}
scopedEval('alert("hello, "+some_var)') ;

The code to be eval-ed relies on the existence of a few variables, so I need them to be left untouched. 要评估的代码依赖于一些变量的存在,因此我需要保持不变。

How can I instruct Closure Compiler to do that? 如何指示Closure Compiler执行此操作?

PS: PS:
Please disregard the issue about the use of eval being a bad practice. 请忽略有关使用eval是一种不良做法的问题。 That's another matter entirely. 这完全是另一回事。

There might be some Closure Compiler options allowing this sort of thing specifically, but failing that, I would tackle the problem one of these two ways: 可能会有一些Closure Compiler选项专门允许这种事情,但是如果失败,我将通过以下两种方法之一解决问题:

Option 1 选项1

Create a global object to store your variables, and then use the js_externs option to prevent it from being munged: 创建一个全局对象来存储您的变量,然后使用js_externs选项防止它被蒙住:

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @js_externs vars
// ==/ClosureCompiler==
vars = {};

Then you can apply string properties to this object that should be left untouched 然后,您可以将字符串属性应用于该对象,该属性应保持不变

function scopedEval(code){
    vars['some_var'] = 'world';
    return eval('('+code+')');
}
scopedEval('alert("hello, "+vars["some_var"])');

Option 2 选项2

If for some reason vars['some_var'] won't work for you and you need to use some_var literally inside the eval ed code, then you can use with to get around this. 如果由于某种原因vars['some_var']对您不起作用,而您需要在eval代码中直接使用some_var ,则可以使用with来解决此问题。 In this case, you don't need to declare vars as an extern. 在这种情况下,您无需将vars声明为extern。

function scopedEval(code){
    var vars = {
      "some_var": "world"
    };
    with(vars) {
      return eval('('+code+')');
    }
}
scopedEval('alert("hello, "+some_var)');

I'll leave it up to your discretion whether or not you feel dirty using the two features of JavaScript that attract the most vitriol together, namely with and eval . 无论您使用JavaScript的两个吸引最多硫酸的功能( witheval是否感到脏,我都会自行决定。

One option is to use the function constructor: 一种选择是使用函数构造函数:

var scopedEval = new Function(
    "code", 
    "var some_var = 'world'; return eval('('+code+')');");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM