@babel/plugin-transform-computed-properties

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 = (
  16. _obj = {},
  17. _defineProperty(_obj, "x" + foo, "heh"),
  18. _defineProperty(_obj, "y" + bar, "noo"),
  19. _defineProperty(_obj, "foo", "foo"),
  20. _defineProperty(_obj, "bar", "bar"),
  21. _obj
  22. );

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. ["@babel/plugin-transform-computed-properties", {
  4. "loose": true
  5. }]
  6. ]
  7. }

Via CLI

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

Via Node API

  1. require("@babel/core").transform("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 namesuse simple assignments instead of being defined. This is unlikely to be an issuein production code.

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. var obj = (
  3. _obj = {},
  4. _obj["x" + foo] = "heh",
  5. _obj["y" + bar] = "noo",
  6. _obj.foo = "foo",
  7. _obj.bar = "bar",
  8. _obj
  9. );

You can read more about configuring plugin options here