webpack 之js兼容性处理
webpack 之js兼容性处理
// 用来拼接绝对路径的方法
const {resolve} = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
// webpack 配置
// 入口起点
entry : './src/index.js',
// 输出
output : {
// 输出文件名
filename : 'js/built.js',
// 输出路径
path : resolve(__dirname, 'dist')
},
// loader 配置
module : {
rules : [
/*
js 兼容性处理:babel-loader @babel/core @babel/preset-env
1. 基本js兼容性处理 --> @babel/preset-env
问题:只能转换基本语法,如Promise不能转换
2. 全部js兼容性处理 --> @babel/polyfill 使用时直接在js文件里面引入:import '@babel/polyfill'
问题:我只要解决部分兼容性问题,但是将所有兼容性代码全部引入,体积太大了
3. 需要做兼容性处理的就做:按需加载 --> core-js
*/
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
// 预设:指示babel做怎样的兼容性处理
presets: [
[
'@babel/preset-env',
{
// 按需加载
useBuiltIns: 'usage',
// 指定 core-js版本
corejs: {
version: 3
},
// 指定兼容性做到哪个版本浏览器
targets: {
chrome: '60',
firefox: '60',
ie: '9',
safari: '10',
edge: '17'
}
}
]
]
}
}
]
},
// plugins 的配置
plugins : [
// 详细 plugins 的配置
// html-webpack-plugin
// 功能:默认会创建一个空的html文件,自动引入打包输出的所有资源(js/css)
new HtmlWebpackPlugin({
// 增加一个配置
// 复制 './src/index.html' 文件,并自动引入打包输出的所有资源(js/css)
template : './src/index.html'
})
],
//模式
mode : 'development', // 生产模式
// mode : 'production' // 开发模式
}

浙公网安备 33010602011771号