为什么需要babel?
ES6+ 的语法、TypeScript、React 项目 JSX 都是离不开 Babel 的。
Babel是一个
工具链
,主要用于旧浏览器或者环境中将ECMAScript 2015+代码转换为向后兼容版本的JavaScript
![](https://i-blog.csdnimg.cn/blog_migrate/7a1ea8769edb2866b60ba58f0c893d3e.png)
Babel命令行使用
babel本身可以作为一个独立的工具
(和postcss一样),不和webpack等构建工具配置来单独使用。
- @babel/core:babel的核心代码
- @babel/cli:可以让我们在命令行使用babel
安装:
npm install @babel/cli @babel/core -D
- src:是源文件的目录;
- --out-dir:指定要输出的文件夹dist;
使用:
npx babel src --out-dir dist
插件的使用
- 箭头函数
npm install @babel/plugin-transform-arrow-functions -D
npx babel src --out-dir dist --plugins=@babel/plugin-transform-arrow-functions
- const 转换 var
npm install @babel/plugin-transform-block-scoping -D
npx babel src --out-dir dist --plugins=@babel/plugin-transform-block-scoping
,@babel/plugin-transform-arrow-functions
(
箭头函数 & const 转换 var
)
Babel的预设preset
如果要转换的内容过多,一个个设置是比较麻烦的,可以使用预设(preset)
安装@babel/preset-env预设。
npm install @babel/preset-env -D
执行:
npx babel src --out-dir dist --presets=@babel/preset-env
webpack 中使用 babel
安装:
npm install babel-loader -D
![](https://i-blog.csdnimg.cn/blog_migrate/cbe9d54ab7962a247f2f681be103b711.png)
webpack 中使用 babel-preset
安装:
npm install @babel/preset-env
- 定义 Babel 配置文件
module.exports = {
presets: ["@babel/preset-env"],
};
- webpack.config.js
const path = require("path");
module.exports = {
entry: "./src/main.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中
clean: true, // 自动将上次打包目录资源清空
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/, // 排除node_modules代码不编译
loader: "babel-loader",
},
],
}
mode: "development",
};
npx webpack
打包后的 dist/static/js/main.js
文件查看,会发现箭头函数等 ES6 语法已经转换了。