@babel/plugin-transform-arrow-functions
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
此插件已包含在 @babel/preset-env 中
示例
输入
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());
输出
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
- Bun
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
bun add --dev @babel/plugin-transform-arrow-functions
用法
通过配置文件(推荐)
无配置选项时:
{
"plugins": ["@babel/plugin-transform-arrow-functions"]
}
使用配置选项时:
{
"plugins": [["@babel/plugin-transform-arrow-functions", { "spec": true }]]
}
通过命令行
babel --plugins @babel/plugin-transform-arrow-functions script.js
通过 Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-arrow-functions"],
});
配置选项
spec
boolean,默认值 false
Using spec mode with the above example produces:Example
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 -
添加运行时检查,确保函数不会被实例化
-
为箭头函数添加名称
你可以在此处阅读更多关于配置插件选项的信息。