Prevent Google Closure Compiler from renaming settings objects

后端 未结 6 2043
礼貌的吻别
礼貌的吻别 2020-12-06 05:56

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 though

6条回答
  •  星月不相逢
    2020-12-06 06:15

    I think what you're really trying to do is stop it from renaming property names on the object coming back from an AJAX controller on the server, which obviously would break the call.

    So when you call

    $.ajax({
        data: { joe: 'hello' },
        success: function(r) {
            alert(r.Message);
        }
    });
    

    You want it to leave Message alone, correct?

    If so that's done by the way you mentioned earlier, but it's compiled nicely to .Message in the output. The above becomes:

    var data = {};
    data['joe'] = 'hello';
    
    $.ajax({
        data: data,
        /**
        @param Object. r
        */
        success: function (r) {
            alert(r['Message']);
        }
    });
    

    Minifies now to:

    $.ajax({data:{joe:"hello"},success:function(a){alert(a.Message)}});
    

    By using r['Message'] instead of r.Message, you prevent the property rename by the minifier. That's called the export method, which as you'll notice in the Closure Compiler documentation is preferred over externs. That is, if you use the externs method to do this instead, you're going to make several people at Google angry. They even put an ID on the heading named, "no": http://code.google.com/closure/compiler/docs/api-tutorial3.html#no

    That said, you can also do this using the externs method, and here it is in all its weirdness:

    externs.js

    /** @constructor */
    function Server() { };
    
    /** @type {string} */
    Server.prototype.Message;
    

    test.js

    $.ajax({
        data: { joe: 'hello' },
        /**
        @param {Server} r
        */
        success: function (r) {
            alert(r.Message);
        }
    });
    

    C:\java\closure>java -jar compiler.jar --externs externs.js --js jquery-1.6.js --js test.js --compilation_level ADVANCED_OPTIMIZATIONS --js_output_file output.js

    And out comes:

    $.ajax({data:{a:"hello"},success:function(a){alert(a.Message)}});
    

提交回复
热议问题