简介
ES6 的某些高级语法在浏览器环境甚至是 Node.js 环境中无法执行。
Babel 是一个广泛使用的转码器,可以将 ES6 代码转为 ES5 代码,从而在现有环境执行执行。
这意味着,你可以现在就用 ES6 编写程序,而不用担心现有环境是否支持。下面是一个例子:
// 转码前
input.map(item => item + 1);
// 转码后
input.map(function (item) {
return item + 1;
});
// 转码前
input.map(item => item + 1);
// 转码后
input.map(function (item) {
return item + 1;
});
上面的原始代码用了箭头函数,Babel 将其转为普通函数,就能在不支持箭头函数的 JavaScript 环境执行了。
更多 Babel 转换器的使用,见其 官方文档
安装 babel
Babel 官方文档推荐使用如下方式安装:
npm install --save-dev @babel/core @babel/cli @babel/preset-env
npm install --save-dev @babel/core @babel/cli @babel/preset-env
其中,@babel/core
为 Babel 核心包;@babel/cli
为命令行工具;@babel/preset-env
是一系列插件的集合,包含了我们在 babel6 中常用的 es2015,es2016, es2017 等最新的语法转化插件,允许我们使用最新的 js 语法。
查看是否安装成功
babel --version
babel --version
Babel 配置
Babel 的配置文件是.babelrc,存放在项目的根目录下,该文件用来设置转码规则和插件,基本格式如下。
{
"presets": [],
"plugins": []
}
{
"presets": [],
"plugins": []
}
presets
字段设定转码规则,例如:
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "usage",
"corejs": "3.6.5"
}
]
]
}
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "usage",
"corejs": "3.6.5"
}
]
]
}
更多设置可以看 官方文档 - @babel/preset-env
使用命令转码
我们先准备一个使用 ES6 语法编写的 JS 文件,命名为 demo.js
:
let input = [1, 2, 3]
input = input.map(item => item + 1)
console.log(input)
let input = [1, 2, 3]
input = input.map(item => item + 1)
console.log(input)
我们在命令行使用如下命令,将 js 文件进行转码:
babel [src] -o [compiled]
babel [src] -o [compiled]
例如:
// 未全局安装 babel-cli
.\node_modules\.bin\babel .\babel\demo.js -o .\babel\compiled.js
// 如果全局安装了 babel-cli
babel .\babel\demo.js -o .\babel\compiled.js
// 未全局安装 babel-cli
.\node_modules\.bin\babel .\babel\demo.js -o .\babel\compiled.js
// 如果全局安装了 babel-cli
babel .\babel\demo.js -o .\babel\compiled.js
转码后的 compiled.js
文件:
"use strict";
let input = [1, 2, 3];
input = input.map(item => item + 1);
console.log(input);
"use strict";
let input = [1, 2, 3];
input = input.map(item => item + 1);
console.log(input);
当然,我们也可以对整个文件夹的文件进行转码:
babel [dir] -d [compiledDir]
babel [dir] -d [compiledDir]
自定义脚本
在实际开发中,如果我们每次都敲这么长的命令肯定很麻烦,所以我们可以自定义脚本的方式,将这个命令保存起来,直接用 npm run xxx
的方式执行就可以。
自定义脚本需要在 package.json
中添加,例如,上述的案例可以写成:
"scripts": {
"babel": ".\\node_modules\\.bin\\babel .\\babel\\demo.js -o .\\babel\\compiled.js"
},
"scripts": {
"babel": ".\\node_modules\\.bin\\babel .\\babel\\demo.js -o .\\babel\\compiled.js"
},
或者直接转码整个文件夹:
"scripts": {
"babel": ".\\node_modules\\.bin\\babel .\\babel -d .\\babel\\compiled"
},
"scripts": {
"babel": ".\\node_modules\\.bin\\babel .\\babel -d .\\babel\\compiled"
},
使用的时候,只需要执行 npm run babel
即可。