@babel/plugin-transform-arrow-functions
这个插件包含在 @babel/preset-env 中
示例
🌐 Example
在
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());
安装
🌐 Installation
- 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
用法
🌐 Usage
使用配置文件(推荐)
🌐 With a configuration file (Recommended)
没有选项:
🌐 Without options:
{
"plugins": ["@babel/plugin-transform-arrow-functions"]
}
有选项:
🌐 With options:
{
"plugins": [["@babel/plugin-transform-arrow-functions", { "spec": true }]]
}
通过 CLI
🌐 Via CLI
babel --plugins @babel/plugin-transform-arrow-functions script.js
通过 Node API
🌐 Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-arrow-functions"],
});
选项
🌐 Options
spec
boolean,默认值为 false。
在上面的示例中使用规范模式会产生: 🌐 Using spec mode with the above example produces:例子
此选项启用以下功能:
🌐 This option enables the following:
- 把生成的函数包在
.bind(this)里,并保持函数内部this的使用不变,而不是使用重命名的this。 - 添加运行时检查以确保函数未实例化。
- 为箭头函数添加名称。
你可以在这里了解更多关于配置插件选项的内容