Search code examples
google-closure-compiler

Google Closure Compiler doesn't rename some properties


It's been documented that the Google Closure Compiler using advanced optimization will rename some properties but not others. However, there seems to be no explanation as to why the it fails to rename the properties "id" and "visibility" in the following code:

const model = {
    age: 5,
    id: 1234,
    visibility: true,
    skills: 4,
    hair: 667
}


function doSomething() {
    var s = Object.create(model);
    console.log("Age: " + model.age);

    s.visibility = "john";
    s.age = 2;
    s.skills = 5;
    s.hair = 999;

    model.age = 6;
    return s;
}

doSomething();

And this is the compiler settings:

java -jar closure-compiler/compiler.jar \
    --compilation_level ADVANCED_OPTIMIZATIONS \
    --js_output_file scripts/release/test-min.js \
    --warning_level VERBOSE \
    --language_out ECMASCRIPT5 \
    --language_in=ES6_Strict \
    --js scripts/temp/test.js

You'll notice that there are not externs.


Solution

  • Closure-compiler will only rename items if it believes it can safely do so. There are two types of properties that can be renamed:

    • Property names which do not exist on any extern object
    • Properties where the compiler has enough type information to rename even when the property exists on an extern object.

    id and visibility both exist as properties in the default externs. Therefore they cannot be renamed unless enough type information is present.

    If any object has an unknown type and has a property of the same name, type-based renaming will not rename it. This unknown property can even be in the default externs.

    The compiler does much better renaming actual classes than anonymous objects. You might try seeing what happens if you make model and actual class.