I wish to rename object property in ADVANCED_OPTIMIZATIONS mode.
Code before optimization:
/**
* @constructor
*/
function Container() {
var items = [];
Object.defineProperty(this, 'items', {
set: function(value) {
items = value;
},
get: function() {
return items;
}
});
}
var container = new Container();
container.items = [1,2,3];
console.log(container.items);
After optimization:
var b = new function() {
var a = [];
Object.defineProperty(this, "items", {set:function(c) {
a = c
}, get:function() {
return a
}})
};
b.e = [1, 2, 3];
console.log(b.e);
Closure Compiler not renamed the property name - "items".
As @owler correctly answered, Closure-compiler can not rename Object.defineProperty
created properties because they are always quoted. Instead, use Object.defineProperties
as they may be either quoted or unquoted.
/**
* @constructor
*/
function Container() {
var items = [];
Object.defineProperties(this, {
items$: {
set: function(value) {
items = value;
},
get: function() {
return items;
}
}
});
}
var container = new Container();
container.items$ = [1,2,3];
console.log(container.items$);
Note: Properties defined via Object.defineProperties are not eligible for type-based renaming and as such will only be renamed if the property is not defined on any type in the externs set. As such, my example replaces the items
property with items$
.
Closure Compiler will not rename properties that are ever referenced with a quoted string:
Whenever possible, use dot-syntax property names rather than quoted strings. Use quoted string property names only when you don't want Closure Compiler to rename a property at all.
See https://developers.google.com/closure/compiler/docs/api-tutorial3#enable-ui
Since Object.defineProperty
requires a string for the property name I'm guessing there is no way to get Closure Compiler to rename it. If you really need this, you could ask on the Closure Compiler Forum if there is some way to trick the compiler into doing that.