@babel/plugin-transform-computed-properties
此插件包含在 @babel/preset-env
中
¥This plugin is included in @babel/preset-env
示例
¥Example
输入
¥In
var obj = {
["x" + foo]: "heh",
["y" + bar]: "noo",
foo: "foo",
bar: "bar",
};
输出
¥Out
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
- Yarn
- pnpm
npm install --save-dev @babel/plugin-transform-computed-properties
yarn add --dev @babel/plugin-transform-computed-properties
pnpm add --save-dev @babel/plugin-transform-computed-properties
用法
¥Usage
使用配置文件(推荐)
¥With a configuration file (Recommended)
没有选项:
¥Without options:
{
"plugins": ["@babel/plugin-transform-computed-properties"]
}
有选项:
¥With options:
{
"plugins": [
[
"@babel/plugin-transform-computed-properties",
{
"loose": true
}
]
]
}
通过 CLI
¥Via CLI
babel --plugins @babel/plugin-transform-computed-properties script.js
通过 Node API
¥Via Node API
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.
{
"assumptions": {
"setComputedProperties": true
}
}
示例
¥Example
输入
¥In
var obj = {
["x" + foo]: "heh",
["y" + bar]: "noo",
foo: "foo",
bar: "bar",
};
输出
¥Out
当 setComputedProperties
为 true
时。
¥When setComputedProperties
is true
.
var _obj;
var obj = ((_obj = {}),
(_obj["x" + foo] = "heh"),
(_obj["y" + bar] = "noo"),
(_obj.foo = "foo"),
(_obj.bar = "bar"),
_obj);
当 setComputedProperties
为 false
时。
¥When setComputedProperties
is false
.
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);