Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

javascript - Prevent Google Closure Compiler from renaming settings objects

I'm trying to get the Google Closure Compiler to not rename objects when passed as settings or data to a function. By looking at the annotations present in jQuery, I thought this would work:

/** @param {Object.<string,*>} data */
window.hello = function(data) {
    alert(data.hello);
};
hello({ hello: "World" });

However, it ends up like this:

window.a = function(b) {
  alert(b.a)
};
hello({a:"World"});

The ajax function found here has this annotation and it appears to work. So, why won't this? If data is the return value from an external source or a settings object I'd like to be able to tell the compiler to not touch it, using the this["escape"] trick is to intrusive for something like this in my opinion.

Here's a better example

function ajax(success) {
      // do AJAX call
    $.ajax({ success: success });
}
ajax(function(data) {
    alert(data.Success);
});

Output:

$.b({c:function(a){alert(a.a)}});

success has been renamed to c and Success (with a capital S) has been renamed to a.

I now compile the same code with the jQuery 1.6 externs file and get the following output:

$.ajax({success:function(a){alert(a.a)}});

It also produces a warning that the property Success is not defined, as I would expect, but it cannot rename Success to simply a, that will still break my code. I look at the annotation present for the ajax and I find this type expression {Object.<string,*>=}, I annotate my code accordingly, and recompile. Still not working...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since your focus seems to be on the source rather than the output, it seems like what you're focused on is DRY (Don't Repeat Yourself). Here's an alternative DRY solution.

You can run the Closure Compiler with --create_name_map_files. Doing so emits a file named _props_map.out. You can have your JSON-emitting server-side calls (ASP.Net MVC or whatever it might be) use these maps when emitting their JSON, so they're actually emitting minified JSON that leverages the renames the Closure Compiler performed. This way you can change the name of a variable or property on your Controller and your scripts, add more, etc, and the minification carries through from the scripts all the way back to the Controller output. All of your source, including the Controller, continues to be non-minified and easy to read.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...