我们打开项目,在index.js 中写一些ES6 的语法,如下。
const arr = [
new Promise( () => {} ),
new Promise( () => {} )
];
arr.map(item => {
console.log(item)
});
然后我们使用打包命令 npm run bundle 或者 npx webpack
在浏览器中打开页面,会报错。主要是使用了ES6 的语法,但浏览器不支持。
这种情况,我们可以使用babel 将ES6 语法代码 转换为 ES5 语法代码。
我们可以查看babel 的官方网站 https://babeljs.io/ ,在官方网站上就给了我们在webpack 中使用babel 的详细指南。
我们可以在babel 官网 > Setup 然后选中 “webpack” 就有在webpack 中使用babel 的详细指南。
按照官网指南,我们首先下载两个包,使用命令
npm install --save-dev babel-loader @babel/core
接着添加一下module 中的rule > loader, 如下
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
]
接着,我们再下载一个包preset-env ,使用如下命令
npm install @babel/preset-env --save-dev
然后,我们更改一下loader 的配置如下。
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
present: ["@babel/preset-env"]
}
}
然后再打包,浏览器就可以正常打开网页了。
完整的webpack.config.js 如下
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
module.exports = {
mode: "development",
devtool: "cheap-eval-module-source-map",
devServer: {
contentBase: './dist',
open: true,
hot: true,
hotOnly: true
},
entry: {
main: "./src/index.js"
},
module: {
rules: [{
test: /\.(png|jpg|gif)$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'imgs/'
}
}
},{
test: /\.scss$/,
use: ['style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 2,
modules:true
}
},
'sass-loader',
'postcss-loader']
},{
test: /\.css$/,
use: ['style-loader',
'css-loader',
'postcss-loader']
},{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"]
}
}
]
},
output: {
// publicPath: "http://cdn.com.cn",
// publicPath: "/",
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new CleanWebpackPlugin(),
new webpack.HotModuleReplacementPlugin()
]
}
我们发现,打包生成的es5代码,还存在这Promise 对象。一些低版本的浏览器还是不能正确运行代码。
这时候,我们需要用到 polyfill 。在babel 官网下的 docs > Usage > polyfill 。
我们先安装 polyfill 使用命令
npm install --save @babel/polyfill
然后呢,我们需要在所有代码运行前,引入 polyfill , 它会补充我们缺少的内容
require("@babel/polyfill");
或者
import "@babel/polyfill";
于是,我们在 index.js 第一行插入上面的import 语句。像下面。
import "@babel/polyfill";
const arr = [
new Promise( () => {} ),
new Promise( () => {} )
];
arr.map(item => {
console.log(item)
});
下面两个图,上面是使用polyfill 之前打包的结果,下面是使用了polyfill 之后打包的结果。main.js 增加了很多的内容,就是因为polyfill 加入了很多实现一些对象的代码。这个时候,polyfill 是加了很多的实现,实际上,我们的代码,只需要它帮助我们实现 Promise 对象,和map 函数。这时候,我们可以简单配置一下。
我们主要是配置一下babel 的preset 。可以在官网 docs > general > presets 中查看
我们来修改一下webpack.config.js 中babel 的presets 配置如下。
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: [["@babel/preset-env",{
useBuiltIns: 'usage'
}]]
}
}
然后我们打包,就会发现,main.js 没那么大了。如下