输入
var obj = {
["x" + foo]: "heh",
["y" + bar]: "noo",
foo: "foo",
bar: "bar"
};
输出
var _obj;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var obj = (
_obj = {},
_defineProperty(_obj, "x" + foo, "heh"),
_defineProperty(_obj, "y" + bar, "noo"),
_defineProperty(_obj, "foo", "foo"),
_defineProperty(_obj, "bar", "bar"),
_obj
);
npm install --save-dev babel-plugin-transform-es2015-computed-properties
.babelrc
(推荐).babelrc
未包含选项:
{
"plugins": ["transform-es2015-computed-properties"]
}
包含选项:
{
"plugins": [
["transform-es2015-computed-properties", {
"loose": true
}]
]
}
babel --plugins transform-es2015-computed-properties script.js
require("babel-core").transform("code", {
plugins: ["transform-es2015-computed-properties"]
});
loose
boolean
,默认为 false
就像类中的方法赋值一样,在松散模式下,计算属性名称使用简单的赋值方式而没有使用定义。这在生产代码中不太可能成为问题。
输入
var obj = {
["x" + foo]: "heh",
["y" + bar]: "noo",
foo: "foo",
bar: "bar"
};
输出
var _obj;
var obj = (
_obj = {},
_obj["x" + foo] = "heh",
_obj["y" + bar] = "noo",
_obj.foo = "foo",
_obj.bar = "bar",
_obj
);