@babel/plugin-proposal-class-properties

Example

Below is a class with four class properties which will be transformed.

  1. class Bork {
  2. //Property initializer syntax
  3. instanceProperty = "bork";
  4. boundFunction = () => {
  5. return this.instanceProperty;
  6. };
  7. //Static class properties
  8. static staticProperty = "babelIsCool";
  9. static staticFunction = function() {
  10. return Bork.staticProperty;
  11. };
  12. }
  13. let myBork = new Bork;
  14. //Property initializers are not on the prototype.
  15. console.log(myBork.__proto__.boundFunction); // > undefined
  16. //Bound functions are bound to the class instance.
  17. console.log(myBork.boundFunction.call(undefined)); // > "bork"
  18. //Static function exists on the class.
  19. console.log(Bork.staticFunction()); // > "babelIsCool"

Installation

  1. npm install --save-dev @babel/plugin-proposal-class-properties

Usage

.babelrc

Without options:

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

With options:

  1. {
  2. "plugins": [
  3. ["@babel/plugin-proposal-class-properties", { "loose": true }]
  4. ]
  5. }

Via CLI

  1. babel --plugins @babel/plugin-proposal-class-properties script.js

Via Node API

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

Options

loose

boolean, defaults to false.

When true, class properties are compiled to use an assignment expression instead of Object.defineProperty.

For an explanation of the consequences of using either, see Definition vs. Assignment (TL;DR in Part 5)

Example

  1. class Bork {
  2. static a = 'foo';
  3. static b;
  4. x = 'bar';
  5. y;
  6. }

Without { "loose": true }, the above code will compile to the following, using Object.defineProperty:

  1. var Bork = function Bork() {
  2. babelHelpers.classCallCheck(this, Bork);
  3. Object.defineProperty(this, "x", {
  4. configurable: true,
  5. enumerable: true,
  6. writable: true,
  7. value: 'bar'
  8. });
  9. Object.defineProperty(this, "y", {
  10. configurable: true,
  11. enumerable: true,
  12. writable: true,
  13. value: void 0
  14. });
  15. };
  16. Object.defineProperty(Bork, "a", {
  17. configurable: true,
  18. enumerable: true,
  19. writable: true,
  20. value: 'foo'
  21. });
  22. Object.defineProperty(Bork, "b", {
  23. configurable: true,
  24. enumerable: true,
  25. writable: true,
  26. value: void 0
  27. });

However, with { "loose": true }, it will compile using assignment expressions:

  1. var Bork = function Bork() {
  2. babelHelpers.classCallCheck(this, Bork);
  3. this.x = 'bar';
  4. this.y = void 0;
  5. };
  6. Bork.a = 'foo';
  7. Bork.b = void 0;

You can read more about configuring plugin options here

References