Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 752
isar Avatar asked Mar 18 '18 17:03

isar


People also ask

Can we use arrow function in class?

You should avoid using arrow functions in class as they won't be the part of prototype and thus not shared by every instance. It is same as giving the same copy of function to every instance.

How are arrow functions () => {} different than traditional function expressions?

Regular functions created using function declarations or expressions are constructible and callable. Since regular functions are constructible, they can be called using the new keyword. However, the arrow functions are only callable and not constructible, i.e arrow functions can never be used as constructor functions.

What is Babel plugin proposal class properties?

What is @babel/plugin-proposal-class-properties? This plugin transforms static class properties as well as properties declared with the property initializer syntax.

Is arrow function declaration or expression?

An arrow function expression is an anonymous function expression written with the “fat arrow” syntax ( => ). Like traditional function expressions, arrow functions are not hoisted, and so you cannot call them before you declare them. They are also always anonymous—there is no way to name an arrow function.


1 Answers

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

  • babel-preset-stage-0
  • babel-preset-stage-1
  • babel-preset-stage-2

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

like image 154
GG. Avatar answered Sep 20 '22 10:09

GG.