# Babel
官方文档 https://www.webpackjs.com/loaders/babel-loader#root
JavaScript 编译器。
主要用于将 ES6 语法编写的代码转换为向后兼容的 JavaScript 语法,以便能够运行在当前和旧版本的浏览器或其他环境中
# 安装
npm i babel-loader @babel/core @babel/preset-env -D
1
- babel-loader:用于在 webpack 构建过程中将 JavaScript 文件从 ES6+转换为 ES5,以便在旧版浏览器中运行。
- @babel/core:这是 Babel 编译器的核心包,提供转译 JavaScript 代码的功能。
- @babel/preset-env:这是 Babel 的一个预设,用于将 ES6+代码转换为向后兼容的 JavaScript 版本,以便在当前和旧版浏览器中运行。
# 配置文件
配置文件由很多种写法:
babel.config.*
1:新建文件,位于项目根目录
babel.config.js
babel.config.json
.babelrc.*
1:新建文件,位于项目根目录
.babelrc
.babelrc.js
.babelrc.json
package.json
中babel
:不需要创建文件,在原有文件基础上写
Babel 会查找和自动读取它们,所以以上配置文件只需要存在一个即可
# babel.config.js
基础配置
// babel.config.js
module.exports = {
// 预设
presets: ["@babel/preset-env"],
};
1
2
3
4
5
2
3
4
5
# webpack.config.js 配置 Babel
- 配置在
loader
之中
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/, // 排除node_modules代码不编译
loader: "babel-loader",
},
],
},
};
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
- 完整
webpack.config.js
const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
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",
},
],
},
plugins: [
// ... 其他配置
],
mode: "development",
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25