使用Babel可以让代码中较为新的语法被编译成浏览器广泛支持的旧的语法,无需等待浏览器去支持新语法。
安装babel:
npm install @babel/core @babel/cli -D在命令行中使用
npx babel demo.js --out-dir dist
// demo.js 是源文件,dist是目标文件夹,也可以使用--out-file res.js输出到特定文件中此时还不能将ES6的箭头语法转化,需要安装一个转换箭头函数的插件:
npm install @babel/plugin-transform-arrow-functions -D使用插件再进行转化,使用方式是加上–plugins参数:
npx babel demo.js --out-file res.js --plugins=@babel/plugin-transform-arrow-functions使用块级作用域转换插件,安装:
npm install @babel/plugin-transform-block-scoping -D使用:
npx babel demo.js --out-file res.js --plugins=@babel/plugin-transform-arrow-functions,@babel/plugin-transform-block-scoping原代码:
const message = "hello world";
const names = ["abc", "cba", "qwe"];
names.array.forEach(element => {
console.log(element);
});结果:
var message = "hello world";
var names = ["abc", "cba", "qwe"];
names.array.forEach(function (element) {
console.log(element);
});
使用babel预设来简化参数配置,安装:
npm install @babel/preset-env -D使用:
npx babel demo.js --out-file res.js --presets=@babel/preset-env结果文件:
"use strict";
var message = "hello world";
var names = ["abc", "cba", "qwe"];
names.array.forEach(function (element) {
console.log(element);
});
在webpack中使用babel-loader
首先要安装babel-loader:
npm install babel-loader -D接着在webpack.config.js中添加配置,两种使用插件的方法都已经列出:
{
test: /\.js$/,
use:{
loader: "babel-loader",
options: {
// plugins:[
// "@babel/plugin-transform-arrow-functions",
// "@babel/plugin-transform-block-scoping"
// ]
presets:[
"@babel/preset-env"
]
}
}
}可以将babel的配置信息单独抽取出来,形成一个babel.config.js文件:
module.exports={
presets:[
"@babel/preset-env"
]
}在webpack.config.js中的配置:
{
test: /\.js$/,
loader: "babel-loader"
}