1. 使用Babel处理ES6代码
一些 低版本的 IE 浏览器 无法识别 ES6 语法,此时就需要通过 Babel 进行 语法降级
1.1 基本使用
babel-loader:处理 JS 文件,把 babel 和 webpack 建立通信桥梁
babel-core:babel 核心库,分析 JS 语法
babel/preset-env:用于语法降级
babel/polyfill:用于实现语法降级的一些缺失,比如:promise、map
-
安装
yarn add babel-loader@8.2.2 @babel/core@7.12.10 -D
yarn add @babel/preset-env@7.12.11 -D
yarn add @babel/polyfill@7.12.1 -D
-
配置
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = { mode: "development", entry: './src/index.js', devtool: 'cheap-module-eval-source-map', devServer: { contentBase: './dist', open: true, hot: true, proxy: { '/my': { target: 'https://api-hmugo-web.itheima.net', secure: false, changeOrigin: true, pathRewrite: { '^/my': '' } } } }, module: { rules: [{ test: /\.js$/, loader: 'babel-loader', options: { presets: ['@babel/preset-env'] }, exclude: /node_module/, }, { test: /\.css$/, use: [ "style-loader", "css-loader", "postcss-loader", ], } ], }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }), new CleanWebpackPlugin(), new webpack.HotModuleReplacementPlugin() ], output: { filename: '[name].js', path: path.resolve(__dirname, 'dist') } }
-
在需要语法降级的 js 文件顶部 引入 polyfill
import '@babel/polyfill'; const promiseArray = [ new Promise(() => {}), new Promise(() => {}) ] promiseArray.map(promise => { console.log('prmise', promise); })
-
打包
yarn run build
1.2 按需引入 polyfill
没有使用 polyfill -> 4.49 KiB 100 行
使用一下 polyfill -> 910 KiB 3568 行
按需引入 polyfill -> 122 KiB 622 行
使用了 polyfill 以后增加了很多代码,是因为它将 ES6 的新特性 用 ES5 全部实现了出来,而我们只需要按需引入就可以了
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: "development",
entry: './src/index.js',
devtool: 'cheap-module-eval-source-map',
devServer: {
contentBase: './dist',
open: true,
// hot: true,
proxy: {
'/my': {
target: 'https://api-hmugo-web.itheima.net',
secure: false,
changeOrigin: true,
pathRewrite: {
'^/my': ''
}
}
}
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
options: {
presets: [ // 提示:这里配置了以后,就不需要在需要语法降级的JS文件顶部引入 polifill 了
['@babel/preset-env', { // 注意:数组的第一项是预设名,第二项是配置项
useBuiltIns: 'usage'
}]
]
},
exclude: /node_module/,
},
{
test: /\.css$/,
use: [
"style-loader",
"css-loader",
"postcss-loader",
],
}
],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
new CleanWebpackPlugin(),
// new webpack.HotModuleReplacementPlugin()
],
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
}
}