Projekt

Obecné

Profil

Stáhnout (2.35 KB) Statistiky
| Větev: | Revize:
1
# babel-plugin-transform-es2015-arrow-functions
2

    
3
> Compile ES2015 arrow functions to ES5
4

    
5
## Example
6

    
7
**In**
8

    
9
```javascript
10
var a = () => {};
11
var a = (b) => b;
12

    
13
const double = [1,2,3].map((num) => num * 2);
14
console.log(double); // [2,4,6]
15

    
16
var bob = {
17
  _name: "Bob",
18
  _friends: ["Sally", "Tom"],
19
  printFriends() {
20
    this._friends.forEach(f =>
21
      console.log(this._name + " knows " + f));
22
  }
23
};
24
console.log(bob.printFriends());
25
```
26

    
27
**Out**
28

    
29
```javascript
30
var a = function a() {};
31
var a = function a(b) {
32
  return b;
33
};
34

    
35
var double = [1, 2, 3].map(function (num) {
36
  return num * 2;
37
});
38
console.log(double); // [2,4,6]
39

    
40
var bob = {
41
  _name: "Bob",
42
  _friends: ["Sally", "Tom"],
43
  printFriends: function printFriends() {
44
    var _this = this;
45

    
46
    this._friends.forEach(function (f) {
47
      return console.log(_this._name + " knows " + f);
48
    });
49
  }
50
};
51
console.log(bob.printFriends());
52
```
53

    
54
[Try in REPL](http://babeljs.io/repl/#?evaluate=true&lineWrap=true&presets=es2015%2Ces2015-loose&experimental=false&loose=false&spec=false&code=var%20a%20%3D%20()%20%3D%3E%20%7B%7D%3B%0Avar%20a%20%3D%20(b)%20%3D%3E%20b%3B%0A%0Aconst%20double%20%3D%20%5B1%2C2%2C3%5D.map((num)%20%3D%3E%20num%20*%202)%3B%0Aconsole.log(double)%3B%20%2F%2F%20%5B2%2C4%2C6%5D%0A%0Avar%20bob%20%3D%20%7B%0A%20%20_name%3A%20%22Bob%22%2C%0A%20%20_friends%3A%20%5B%22Sally%22%2C%20%22Tom%22%5D%2C%0A%20%20printFriends()%20%7B%0A%20%20%20%20this._friends.forEach(f%20%3D%3E%0A%20%20%20%20%20%20console.log(this._name%20%2B%20%22%20knows%20%22%20%2B%20f))%3B%0A%20%20%7D%0A%7D%3B%0Aconsole.log(bob.printFriends())%3B&playground=true)
55

    
56
## Installation
57

    
58
```sh
59
npm install --save-dev babel-plugin-transform-es2015-arrow-functions
60
```
61

    
62
## Usage
63

    
64
### Via `.babelrc` (Recommended)
65

    
66
**.babelrc**
67

    
68
```js
69
// without options
70
{
71
  "plugins": ["transform-es2015-arrow-functions"]
72
}
73

    
74
// with options
75
{
76
  "plugins": [
77
    ["transform-es2015-arrow-functions", { "spec": true }]
78
  ]
79
}
80
```
81

    
82
### Via CLI
83

    
84
```sh
85
babel --plugins transform-es2015-arrow-functions script.js
86
```
87

    
88
### Via Node API
89

    
90
```javascript
91
require("babel-core").transform("code", {
92
  plugins: ["transform-es2015-arrow-functions"]
93
});
94
```
95

    
96
## Options
97

    
98
* `spec` - This option wraps the generated function in `.bind(this)` and keeps uses of `this` inside the function as-is, instead of using a renamed `this`. It also adds a runtime check to ensure the functions are not instantiated.
(2-2/3)