@babel/plugin-transform-arrow-functions

Example

In

  1. var a = () => {};
  2. var a = (b) => b;
  3. const double = [1,2,3].map((num) => num * 2);
  4. console.log(double); // [2,4,6]
  5. var bob = {
  6. _name: "Bob",
  7. _friends: ["Sally", "Tom"],
  8. printFriends() {
  9. this._friends.forEach(f =>
  10. console.log(this._name + " knows " + f));
  11. }
  12. };
  13. console.log(bob.printFriends());

Out

  1. var a = function () {};
  2. var a = function (b) {
  3. return b;
  4. };
  5. const double = [1, 2, 3].map(function (num) {
  6. return num * 2;
  7. });
  8. console.log(double); // [2,4,6]
  9. var bob = {
  10. _name: "Bob",
  11. _friends: ["Sally", "Tom"],
  12. printFriends() {
  13. var _this = this;
  14. this._friends.forEach(function (f) {
  15. return console.log(_this._name + " knows " + f);
  16. });
  17. }
  18. };
  19. console.log(bob.printFriends());

Installation

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

Usage

.babelrc

Without options:

  1. {
  2. "plugins": ["@babel/plugin-transform-arrow-functions"]
  3. }

With options:

  1. {
  2. "plugins": [
  3. ["@babel/plugin-transform-arrow-functions", { "spec": true }]
  4. ]
  5. }

Via CLI

  1. babel --plugins @babel/plugin-transform-arrow-functions script.js

Via Node API

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

Options

spec

boolean, defaults to false.

Example

Using spec mode with the above example produces:

  1. var _this = this;
  2. var a = function a() {
  3. babelHelpers.newArrowCheck(this, _this);
  4. }.bind(this);
  5. var a = function a(b) {
  6. babelHelpers.newArrowCheck(this, _this);
  7. return b;
  8. }.bind(this);
  9. const double = [1, 2, 3].map(function (num) {
  10. babelHelpers.newArrowCheck(this, _this);
  11. return num * 2;
  12. }.bind(this));
  13. console.log(double); // [2,4,6]
  14. var bob = {
  15. _name: "Bob",
  16. _friends: ["Sally", "Tom"],
  17. printFriends() {
  18. var _this2 = this;
  19. this._friends.forEach(function (f) {
  20. babelHelpers.newArrowCheck(this, _this2);
  21. return console.log(this._name + " knows " + f);
  22. }.bind(this));
  23. }
  24. };
  25. console.log(bob.printFriends());

This option enables the following:

  • Wrap the generated function in .bind(this) and keeps uses of this insidethe function as-is, instead of using a renamed this.

  • Add a runtime check to ensure the functions are not instantiated.

  • Add names to arrow functions.

You can read more about configuring plugin options here