@babel/plugin-transform-arrow-functions
資訊
此外掛程式包含在 @babel/preset-env
中
範例
輸入
JavaScript
var a = () => {};
var a = b => b;
const double = [1, 2, 3].map(num => num * 2);
console.log(double); // [2,4,6]
var bob = {
_name: "Bob",
_friends: ["Sally", "Tom"],
printFriends() {
this._friends.forEach(f => console.log(this._name + " knows " + f));
},
};
console.log(bob.printFriends());
輸出
JavaScript
var a = function() {};
var a = function(b) {
return b;
};
const double = [1, 2, 3].map(function(num) {
return num * 2;
});
console.log(double); // [2,4,6]
var bob = {
_name: "Bob",
_friends: ["Sally", "Tom"],
printFriends() {
var _this = this;
this._friends.forEach(function(f) {
return console.log(_this._name + " knows " + f);
});
},
};
console.log(bob.printFriends());
安裝
- npm
- Yarn
- pnpm
npm install --save-dev @babel/plugin-transform-arrow-functions
yarn add --dev @babel/plugin-transform-arrow-functions
pnpm add --save-dev @babel/plugin-transform-arrow-functions
用法
使用設定檔 (建議)
無選項
babel.config.json
{
"plugins": ["@babel/plugin-transform-arrow-functions"]
}
有選項
babel.config.json
{
"plugins": [["@babel/plugin-transform-arrow-functions", { "spec": true }]]
}
透過 CLI
Shell
babel --plugins @babel/plugin-transform-arrow-functions script.js
透過 Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-arrow-functions"],
});
選項
spec
布林值
,預設為 false
。
範例
使用上述範例的 spec 模式會產生
JavaScript
var _this = this;
var a = function a() {
babelHelpers.newArrowCheck(this, _this);
}.bind(this);
var a = function a(b) {
babelHelpers.newArrowCheck(this, _this);
return b;
}.bind(this);
const double = [1, 2, 3].map(
function(num) {
babelHelpers.newArrowCheck(this, _this);
return num * 2;
}.bind(this)
);
console.log(double); // [2,4,6]
var bob = {
_name: "Bob",
_friends: ["Sally", "Tom"],
printFriends() {
var _this2 = this;
this._friends.forEach(
function(f) {
babelHelpers.newArrowCheck(this, _this2);
return console.log(this._name + " knows " + f);
}.bind(this)
);
},
};
console.log(bob.printFriends());
此選項啟用下列功能
-
將產生的函式包覆在
.bind(this)
中,並將函式內的this
使用保留原樣,而不是使用重新命名的this
。 -
加入執行時期檢查,以確保函式未實例化。
-
為箭頭函式加入名稱。
提示
您可以在 此處 閱讀更多有關設定外掛選項的資訊