Arrow functions as class properties using Babel

Can someone explain how Babel in React supports fat arrow functions as class properties? Using Babel Try it out I can see they are not supported:

class Question {

  // Property (not supported)
  myProp = () => {
    return 'Hello, world!';
  }

  // Method (supported)
  myFunc() {
    return 'Hello, world!';
  }

}

Class properties are not supported in ES6 (correct me if I'm wrong) but then in React (with Babel) they work.

I can see the difference between methods and properties using TypeScript Playground but I can't clearly understand if Babel is supporting them or not. Is there some plug-in?

UPDATE:
I can see they are supported using "babel-preset-stage-0".

Answers:

Answer

To support class properties, you need to install and add babel-plugin-transform-class-properties to the plugins setting of your .babelrc (or in your webpack config).

Note that this plugin is also included in

So if you use one of those, you don't need to install babel-plugin-transform-class-properties by yourself.

Answer

As @illiteratewriter suggested class properties are supported from Stage 0 preset. For the time being, they are supported until Stage 2 preset:

The proposal must now additionally have a formal description of the syntax and semantics of the feature (using the formal language of the ECMAScript specification). The description should be as complete as possible, but can contain todos and placeholders. Two experimental implementations of the feature are needed, but one of them can be in a transpiler such as Babel.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.