@babel/plugin-transform-computed-properties
info
这个插件包含在 @babel/preset-env 中
示例
🌐 Example
在
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);
安装
🌐 Installation
- npm
- Yarn
- pnpm
- Bun
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
bun add --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
就像类中的方法赋值一样,在宽松模式下,计算属性名使用简单赋值而不是被定义。这在生产代码中不太可能成为问题。
🌐 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.
caution
考虑迁移到顶层 setComputedProperties 假设。
babel.config.json
{
"assumptions": {
"setComputedProperties": true
}
}
示例
🌐 Example
在
JavaScript
var obj = {
["x" + foo]: "heh",
["y" + bar]: "noo",
foo: "foo",
bar: "bar",
};
出局
当 setComputedProperties 是 true 的时候。
🌐 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);
当 setComputedProperties 是 false 的时候。
🌐 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);
tip
你可以在这里了解更多关于配置插件选项的内容