@babel/plugin-transform-arrow-functions

NOTE: This plugin is included in @babel/preset-env

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 => console.log(this._name + " knows " + f));
  10. },
  11. };
  12. 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

Without options:

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

With options:

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

Via CLI

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

Via Node API

  1. require("@babel/core").transformSync("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(
  10. function(num) {
  11. babelHelpers.newArrowCheck(this, _this);
  12. return num * 2;
  13. }.bind(this)
  14. );
  15. console.log(double); // [2,4,6]
  16. var bob = {
  17. _name: "Bob",
  18. _friends: ["Sally", "Tom"],
  19. printFriends() {
  20. var _this2 = this;
  21. this._friends.forEach(
  22. function(f) {
  23. babelHelpers.newArrowCheck(this, _this2);
  24. return console.log(this._name + " knows " + f);
  25. }.bind(this)
  26. );
  27. },
  28. };
  29. console.log(bob.printFriends());

This option enables the following:

  • Wrap the generated function in .bind(this) and keeps uses of this inside the 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