@babel/plugin-transform-computed-properties

NOTE: This plugin is included in @babel/preset-env

Example

In

  1. var obj = {
  2. ["x" + foo]: "heh",
  3. ["y" + bar]: "noo",
  4. foo: "foo",
  5. bar: "bar",
  6. };

Out

  1. var _obj;
  2. function _defineProperty(obj, key, value) {
  3. if (key in obj) {
  4. Object.defineProperty(obj, key, {
  5. value: value,
  6. enumerable: true,
  7. configurable: true,
  8. writable: true,
  9. });
  10. } else {
  11. obj[key] = value;
  12. }
  13. return obj;
  14. }
  15. var obj = ((_obj = {}),
  16. _defineProperty(_obj, "x" + foo, "heh"),
  17. _defineProperty(_obj, "y" + bar, "noo"),
  18. _defineProperty(_obj, "foo", "foo"),
  19. _defineProperty(_obj, "bar", "bar"),
  20. _obj);

Installation

  1. npm install --save-dev @babel/plugin-transform-computed-properties

Usage

Without options:

  1. {
  2. "plugins": ["@babel/plugin-transform-computed-properties"]
  3. }

With options:

  1. {
  2. "plugins": [
  3. [
  4. "@babel/plugin-transform-computed-properties",
  5. {
  6. "loose": true
  7. }
  8. ]
  9. ]
  10. }

Via CLI

  1. babel --plugins @babel/plugin-transform-computed-properties script.js

Via Node API

  1. require("@babel/core").transformSync("code", {
  2. plugins: ["@babel/plugin-transform-computed-properties"],
  3. });

Options

loose

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.

⚠️ Consider migrating to the top level setComputedProperties assumption.

  1. // babel.config.json
  2. {
  3. "assumptions": {
  4. "setComputedProperties": true
  5. }
  6. }

Example

In

  1. var obj = {
  2. ["x" + foo]: "heh",
  3. ["y" + bar]: "noo",
  4. foo: "foo",
  5. bar: "bar",
  6. };

Out

When setComputedProperties is true.

  1. var _obj;
  2. var obj = ((_obj = {}),
  3. (_obj["x" + foo] = "heh"),
  4. (_obj["y" + bar] = "noo"),
  5. (_obj.foo = "foo"),
  6. (_obj.bar = "bar"),
  7. _obj);

When setComputedProperties is false.

  1. import _defineProperty from "@babel/runtime/helpers/defineProperty";
  2. var _obj;
  3. var obj = ((_obj = {}),
  4. _defineProperty(_obj, "x" + foo, "heh"),
  5. _defineProperty(_obj, "y" + bar, "noo"),
  6. _defineProperty(_obj, "foo", "foo"),
  7. _defineProperty(_obj, "bar", "bar"),
  8. _obj);

You can read more about configuring plugin options here