@babel/plugin-transform-computed-properties

computed-properties - 图1info

This plugin is included in @babel/preset-env

Example

In

JavaScript

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

Out

JavaScript

  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

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-computed-properties
  1. yarn add --dev @babel/plugin-transform-computed-properties
  1. pnpm add --save-dev @babel/plugin-transform-computed-properties

Usage

Without options:

babel.config.json

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

With options:

babel.config.json

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

Via CLI

Shell

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

Via Node API

JavaScript

  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.

computed-properties - 图2caution

Consider migrating to the top level setComputedProperties assumption.

babel.config.json

  1. {
  2. "assumptions": {
  3. "setComputedProperties": true
  4. }
  5. }

Example

In

JavaScript

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

Out

When setComputedProperties is true.

JavaScript

  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.

JavaScript

  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);

computed-properties - 图3tip

You can read more about configuring plugin options here