跳至主要内容

@babel/plugin-transform-computed-properties

信息

此插件包含在 @babel/preset-env

示例

输入

JavaScript
var obj = {
["x" + foo]: "heh",
["y" + bar]: "noo",
foo: "foo",
bar: "bar",
};

输出

JavaScript
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-computed-properties

用法

无选项

babel.config.json
{
"plugins": ["@babel/plugin-transform-computed-properties"]
}

带选项

babel.config.json
{
"plugins": [
[
"@babel/plugin-transform-computed-properties",
{
"loose": true
}
]
]
}

通过 CLI

Shell
babel --plugins @babel/plugin-transform-computed-properties script.js

通过 Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-computed-properties"],
});

选项

loose

boolean,默认为 false

就像类中的方法赋值一样,在松散模式下,计算属性名使用简单赋值而不是定义。这在生产代码中不太可能成为问题。

注意

考虑迁移到顶级的 setComputedProperties 假设。

babel.config.json
{
"assumptions": {
"setComputedProperties": true
}
}

示例

输入

JavaScript
var obj = {
["x" + foo]: "heh",
["y" + bar]: "noo",
foo: "foo",
bar: "bar",
};

输出

setComputedPropertiestrue 时。

JavaScript
var _obj;

var obj = ((_obj = {}),
(_obj["x" + foo] = "heh"),
(_obj["y" + bar] = "noo"),
(_obj.foo = "foo"),
(_obj.bar = "bar"),
_obj);

setComputedPropertiesfalse 时。

JavaScript
import _defineProperty from "@babel/runtime/helpers/defineProperty";

var _obj;

var obj = ((_obj = {}),
_defineProperty(_obj, "x" + foo, "heh"),
_defineProperty(_obj, "y" + bar, "noo"),
_defineProperty(_obj, "foo", "foo"),
_defineProperty(_obj, "bar", "bar"),
_obj);
提示

您可以阅读更多关于配置插件选项的信息 此处