# 三.babel
# 安装
package.json
{
"name": "3.babel-loader",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"@babel/core": "^7.4.3",
"@babel/preset-env": "^7.4.3",
"loader-utils": "^1.2.3",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0"
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 文件
babel-loader.js
let babel = require("@babel/core")
let laoderUtils = require("loader-utils")
function loader(source) {
//this loaderContext
// console.log(Object.keys(this))
console.log(this.resourcePath)
let options = laoderUtils.getOptions(this)
let cb = this.async()
babel.transform(
source,
{
...options,
sourceMap: true,
filename: this.resourcePath.split("/").pop(),
},
function(err, result) {
cb(err, result.code, result.map) //异步
}
)
}
module.exports = loader
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 配置
webpack.config.js
let path = require("path")
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
filename: "build.js",
path: path.resolve(__dirname, "dist"),
},
resolveLoader: {
modules: ["node_modules", path.resolve(__dirname, "loaders")],
// //别名
// alias: {
// loader1: path.resolve(__dirname, "loaders", "loader1.js")
// }
},
devtool: "source-map",
module: {
rules: [
{
test: /\.js$/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
},
],
},
}
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
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
dist/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<script src="build.js"></script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 打包
npx webpack
1
打开浏览器可以看到正确对应的文件名