Skip to main content

@babel/plugin-transform-computed-properties

信息

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

¥This plugin is included in @babel/preset-env

示例

¥Example

输入

¥In

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

输出

¥Out

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);

安装

¥Installation

npm install --save-dev @babel/plugin-transform-computed-properties

用法

¥Usage

¥With a configuration file (Recommended)

没有选项:

¥Without options:

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

有选项:

¥With options:

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

通过 CLI

¥Via CLI

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

通过 Node API

¥Via Node API

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

选项

¥Options

loose

boolean,默认为 false

¥boolean, defaults to false

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

¥Just like method assignment in classes, in loose mode, computed property names use simple assignments instead of being defined. This is unlikely to be an issue in production code.

提醒

考虑迁移到顶层 setComputedProperties 假设。

¥Consider migrating to the top level setComputedProperties assumption.

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

示例

¥Example

输入

¥In

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

输出

¥Out

setComputedPropertiestrue 时。

¥When setComputedProperties is true.

JavaScript
var _obj;

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

setComputedPropertiesfalse 时。

¥When setComputedProperties is false.

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);
提示

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

¥You can read more about configuring plugin options here