@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経由
シェル
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
クラスのメソッド代入と同様に、looseモードでは、計算されたプロパティ名は定義されるのではなく、単純な代入を使用します。これは本番コードでは問題になる可能性は低いでしょう。
注意
トップレベルの 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);
ヒント
プラグインオプションの設定に関する詳細は、こちらをご覧ください。