1.0.1 • Published 5 years ago

babel-plugin-transform-class-property-arrow-functions v1.0.1

Weekly downloads
1,022
License
MIT
Repository
-
Last release
5 years ago

npm version Build Status codecov MIT Licence

babel-plugin-transform-class-property-arrow-functions

This plugin transforms class properties assigned to arrow functions into class methods bound in the class' constructor.

Input code:

class App extends Base {
  handleClick = e => {
    this.props.doSomething();
  }

  handleHover = e => {
    this.props.doSomethingElse();
  }

  render() {
    return new SomeSubComponent(this.handleClick, this.handleHover);
  }
}

Output code:

class App extends Base {
  constructor() {
    this.handleClick = this.handleClick.bind(this);
    this.handleHover = this.handleHover.bind(this);
  }

  handleClick(e) {
    this.props.doSomething();
  }

  handleHover(e) {
    this.props.doSomethingElse();
  }

  render() {
    return new SomeSubComponent(this.handleClick, this.handleHover);
  }
}

Why Use This?

This Medium article walks through some reasons why class properties assigned to arrow functions might not be preferable.

Installation

npm install --save-dev babel-plugin-transform-class-property-arrow-functions

yarn add -D babel-plugin-transform-class-property-arrow-functions

Usage

This plugin does not handle the transformation of class properties themselves. For that, you will likely need to use babel-plugin-proposal-class-properties.

Via .babelrc (Recommended)

{
  "plugins": ["transform-class-property-arrow-functions"]
}

Via CLI

babel --plugins transform-class-property-arrow-functions script.js

Via Node API

require('babel-core').transform('code', {
  plugins: ['transform-class-property-arrow-functions']
});