@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
- 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
使用
使用設定檔 (建議)
無選項
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
布林值
,預設為 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);
提示
您可以在 這裡 閱讀更多關於設定外掛選項的資訊