在 webpack 中使用 babel
具体的 babel 中文网给出了如何在构建工具中使用 babel,详细的可以去官网阅读。
安装以及 webpack 环境搭建
babel 如同 postcss 一样,依赖 loader 来解析 js 的,这两个一个是 babel 的核心库,一个是 loader
sh
pnpm i @babel/core babel-loader -D
pnpm i webpack webpack-cli -D
书写 src/index.js
index.js
js
console.log("入口文件index");
const func = () => {
console.log("abc");
};
new Promise((resolve) => {
resolve();
});
class A {}
async function method() {}
创建.babelrc
和.browserslistrc
文件
babel 本身不会做任何处理,都是依赖预设和插件对 js 代码做的兼容,所以需要安装
sh
pnpm i @babel/preset-env -D
json
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "usage",
"corejs": 3
}
]
],
//
"plugins": []
}
js
last 3 version
> 1%
not ie <= 8
在 webpack 中配置 babel
webpack 的打包过程一定不要忘记,是 loader 先执行,然后才是 webpack 打包。 所以这里一定是 babel-loader 对 index.js 的代码解析了之后,webpack 再对 babel 解析后的代码再次进行打包。
webpack.config.js
js
module.exports = {
mode: "development",
devtool: "source-map",
//loader
module: {
rules: [
{
test: /\.js$/,
use: "babel-loader",
},
],
},
};
安装core-js
和regenerator-runtime
此时执行npx webpack
就会出现报错,找不到 core-js,这是因为 babel-loader 解析之后的代码,依赖了 core-js 的 API 实现以及 regenerator-runtime 对新语法的实现。
sh
pnpm i core-js regenerator-runtime -S
此时再执行打包命令,就成功了。