Babel 7.14 enables class fields & private methods by default in @babel/preset-env

Babel is a free and open-source JavaScript transcompiler. It converts ECMAScript 2015+ (ES6+) code into a backward-compatible version of JavaScript that can be run by older JavaScript engines.

Starting from Babel 7.14 @babel/plugin-proposal-class-properties and @babel/plugin-proposal-private-methods plugins which were included to use the class features are now enabled by default in @babel/preset-env.

@babel/plugin-proposal-class-properties:

This plugin transforms class properties in such a way that we can define class properties using property initializer syntax (i.e., by using the = assignment operator).

In the previous versions of Babel, the class syntax only allows us to define methods inside a class.

Any properties we want on an instance of an object, created within a class, need to be defined inside the constructor method.

class Person {
  constructor() {
    this.name = "Alice";
  }
  getName() {
    return this.name;
  }
}

Starting from Babel 7.14 (ECMAScript 2022), we no longer have to define properties inside the constructor.

  class Person {
    name = "Alice"; //Property initializer syntax
    getName() {
      return this.name;
    }
  }

@babel/plugin-proposal-class-properties plugin also adds support for static fields and methods.

  class Person {
    static department = "IT"; //Static class properties
    static getDepartment() {
      return Person.department;
    };
  }

@babel/plugin-proposal-private-methods:

With this plugin, we can define private class fields and class methods using a hash(#) prefix.

  class Person {
    name = "Alice"; //Property initializer syntax

    #hours = 40; // # means private!

    get #timeSheet() { // private getter
      return this.#hours * 4; // using a private field
    }
  }

Before

In previous versions, we had to include the plugins @babel/plugin-proposal-class-properties and @babel/plugin-proposal-private-methods in the .babelrc.json configuration after installing it in the devDependencies.

npm install @babel/plugin-proposal-private-methods --save-dev
npm install @babel/plugin-proposal-class-properties --save-dev
// .babelrc.json
{
  "presets": ['@babel/preset-env'],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-private-methods"
  ]
}

After

Starting from Babel 7.14, we can remove @babel/plugin-proposal-class-properties and @babel/plugin-proposal-private-methods from the .babelrc.json. They are now available by default in @babel/preset-env.

// .babelrc.json
{
  "presets": ["@babel/preset-env"]
}

Need help on your Ruby on Rails or React project?

Join Our Newsletter