生产环境配置:
const MiniCssExtractPlugin = reuqire(‘mini-css-extract-plugin’);
const OptimizeCssAssetsWepackPlugin =require(‘optimize-css-assets-webpack-plugin’);
const HtmlWebpackPlugin = require(‘html-webpack-plugin’);
// 定义Node.js环境变量:决定browserlist的哪个环境
process.env.NODE_ENV = ‘production’;
const commonCssLoader = [
‘MiniCssExtractPlugin.loader’,
‘css-loader’,
{
// 需要在package.json中定义browserlist·
loader: ‘postcss-loader’,
options: {
ident: ‘postcss’,
plugins:()=>{
require(‘postcss-preset-env’)()
}
}
}
]
module.exports = {
entry: ‘./src/js/index.js’,
output: {
filename: ‘js/built.js’,
path: resolve(__dirname,’build’)
},
module: {
rules:[
{
test:/.css$/
use:[
…commonCssLoader,
]
},
{
test:/.css$/
use:[
…commonCssLoader,
‘less-loader’
]
},
/
正常来讲,一个文件只能被一个loader处理
当一个文件要被多个loader处理,那么一定要指定loader执行的先后顺序
先执行eslint 再执行babel
/
{
// 在package.json中eslintConfig —airbnb
test: /.js$/,
exclude: /node_module/,
enforce: ‘pre’,
loader: ‘eslint-loader’,
options: {
fix: true
}
},
{
// 对js兼容性处理
test: /.js$/,
exclude: /node_module/,
loader: ‘babel-loader’,
options: {
presets: [
[
‘@babel/preset-env’
{
useuiltIns:’useage’,
corejs:{version:3}
targets:
chrome:’60’,
firefox: ‘50’
}
]
]
}
},
{
test: /.(jpg|png|gif)/,
loader: ‘url-loader’,
options:{
limit: 8*1024,
name: ‘[hash:10].[ext]’,
outPath: ‘imgs’,
esModule: false
}
},
{
exclude: /.(js|css|less|html|jpg|png)/,
loader: ‘file-loader’,
options: {
outputPath: ‘media’
}
}
]
},
plugins:[
new MiniCssExtractPlugin ({
filename: ‘css/built.css’
}),
new OptimizeCssAssetsWepackPlugin(),
new HtmlWepackPlugin({
template: ‘./src/index.html’.
minify: {
collapseWhitespce: true, // 压缩空格
removeComments:true // 去除注释
}
})
],
mode: ‘production’
}
Webpack性能优化
开发环境性能优化
生产环境性能优化
开发环境性能优化
优化打包构建速度
优化代码运行的性能
HMR:hot module replacement 热模块替换 /模块热替换
作用:一个模块发生变化,只会重新打包这一个模块而不是打包所有模块
很大程度上提升构建速度
样式文件:可以使用HMR功能:因为style-loader内部实现了
js文件:默认不能使用HMR功能 —>需要修改js代码,添加支持HTML功能的代码
注意:HMR功能对js处理,只能处理非入口js文件
html文件: 默认不能使用HMR功能,同时会导致问题:html文件不能热更新了。
解决方案: 修改entry入口,将html文件引入
entry: [‘./src/js/index.js’,’./src/index.html’] (不用做HMR功能)
devServer:{
contentBase: resolve(__dirname,’build’),
compress: true,
port: 3000,
hot: true // 开启了HMR功能,当修改了webpack配置,新配置想要生效,必须重启webpack服 务
}