@babel/plugin-transform-classes

Caveats

When extending a native class (e.g., class extends Array {}), the super classneeds to be wrapped. This is needed to workaround two problems:

  • Babel transpiles classes using SuperClass.apply(//), but nativeclasses aren't callable and thus throw in this case.
  • Some built-in functions (like Array) always return a new object. Instead ofreturning it, Babel should treat it as the new this.

The wrapper works on IE11 and every other browser with Object.setPrototypeOf or proto as fallback.There is NO IE <= 10 support. If you need IE <= 10 it's recommended that you don't extend natives.

Babel needs to statically know if you are extending a built-in class. For this reason, the "mixin pattern" doesn't work:

  1. class Foo extends mixin(Array) {}
  2. function mixin(Super) {
  3. return class extends Super { mix() {} };
  4. }

To workaround this limitation, you can add another class in the inheritance chain so that Babel can wrap the native class:

  1. const ExtensibleArray = class extends Array {}
  2. class Foo extends mixin(ExtensibleArray) {}

Examples

In

  1. class Test {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. logger () {
  6. console.log("Hello", this.name);
  7. }
  8. }

Out

  1. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2. var Test = function () {
  3. function Test(name) {
  4. _classCallCheck(this, Test);
  5. this.name = name;
  6. }
  7. Test.prototype.logger = function logger() {
  8. console.log("Hello", this.name);
  9. };
  10. return Test;
  11. }();

Installation

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

Usage

  1. // without options
  2. {
  3. "plugins": ["@babel/plugin-transform-classes"]
  4. }
  5. // with options
  6. {
  7. "plugins": [
  8. ["@babel/plugin-transform-classes", {
  9. "loose": true
  10. }]
  11. ]
  12. }

Via CLI

  1. babel --plugins @babel/plugin-transform-classes script.js

Via Node API

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

Options

loose

boolean, defaults to false.

Method enumerability

Please note that in loose mode class methods are enumerable. This is not in linewith the spec and you may run into issues.

Method assignment

Under loose mode, methods are defined on the class prototype with simple assignmentsinstead of being defined. This can result in the following not working:

  1. class Foo {
  2. set bar() {
  3. throw new Error("foo!");
  4. }
  5. }
  6. class Bar extends Foo {
  7. bar() {
  8. // will throw an error when this method is defined
  9. }
  10. }

When Bar.prototype.foo is defined it triggers the setter on Foo. This is acase that is very unlikely to appear in production code however it's somethingto keep in mind.

You can read more about configuring plugin options here