官网:https://babeljs.io/
npm i -D babel-loader @babel/core @babel/preset-env
# 安装babel-loader 和 @babel/core 和 @babel/preset-env
使用 @babel/polyfill
npm i -D @babel/polyfill
# 安装 @babel/polyfill
import ‘@babel/polyfill’ # 在入口文件 index.js 第一行引入 @babel/polyfill
index.js
require("@babel/polyfill")
上面配置好之后,会发现打包后的文件特别大,因为一些没用到的 ES6 语法也被打包了进去,因此需要做如下操作:
删除入口文件 index.js 中的 import ‘@babel/polyfill’
npm install core-js regenerator-runtime -D
入口文件 index.js 中添加import ‘regenerator-runtime/runtime’;
注意:
npm install core-js regenerator-runtime -D // babel7.4之后的兼容浏览器规则包。babel/polyfill被废弃
https://babeljs.io/docs/en/babel-runtime-corejs2
配置:
// webpack.config.js
module.exports = {
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: [
[
'@babel/preset-env',
{
corejs: 3,
useBuiltIns: 'usage',
targets: { // 通过 targets 指定项目运行的环境,打包时会自动判断是否需要去解析转化代码
chrome: '67'
}
}
]
]
}
}]
}
}
$ yarn add @babel/runtime @babel/plugin-transform-runtime -D
如果写的是业务代码,可采用上面方法使用 polyfill 去打包;
如果是开发组件或者库的话,可使用 plugin-transform-runtime
polyfill 会污染全局环境,plugin-transform-runtime 会以闭包的形式帮助组件去引入相关内容
$ yarn add @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators
基于插件处理ES6/ES7中CLASS的特殊语法
src目录
index.js
require("@babel/polyfill")
@log
class A {
constructor() {
}
sum() {
console.log("sum")
}
n = 10;
static m = 20;
static fun() {
console.log("fun")
}
}
function log(target) {
target.decorator = true
}
A.fun()
new A().sum()
console.log(new A().n)
console.log(A.m)
console.log(A.decorator)
function sum() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(100)
}, 1000)
})
}
async function fn() {
let n = await sum()
console.log(n)
}
fn()
webpack.config.dev.js
module:{
rules:[
...
{
test: /\.js$/i,
use: [{
loader: "babel-loader",
options: {
//=>转换的语法预设(ES6->ES5)
presets: [
"@babel/preset-env"
],
//=>基于插件处理ES6/ES7中CLASS的特殊语法
plugins: [
["@babel/plugin-proposal-decorators", {
"legacy": true
}],
["@babel/plugin-proposal-class-properties", {
"loose": true
}],
"@babel/plugin-transform-runtime"
]
},
}],
//=>设置编译时忽略的文件和指定编译目录
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/
}
]
}