@babel/plugin-transform-computed-properties
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
信息
此插件已包含在 @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
- 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
用法
通过配置文件(推荐)
无配置选项时:
babel.config.json
{
"plugins": ["@babel/plugin-transform-computed-properties"]
}
使用配置选项时:
babel.config.json
{
"plugins": [
[
"@babel/plugin-transform-computed-properties",
{
"loose": true
}
]
]
}
通过命令行
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",
};
输出
当 setComputedProperties 为 true 时。
JavaScript
var _obj;
var obj = ((_obj = {}),
(_obj["x" + foo] = "heh"),
(_obj["y" + bar] = "noo"),
(_obj.foo = "foo"),
(_obj.bar = "bar"),
_obj);
当 setComputedProperties 为 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);
提示
你可以在此处阅读更多关于配置插件选项的信息。