初级分析:使用webpack内置的stats
stats:构建统计信息
package.json中使用stats
"scripts": {
"build:stats":"webpack --env production --json > stats.json"
}
复制代码
指定输出的json对象,输出一个json文件
const webpack = require('webpack')
const config = require('./webpack.config.js')('production')
webacpk(config, (err, stats) => {
if(err) {
return console.error(err);
}
if(stats.hasErrors()) {
return console.log(stats.toString("errors-only"))
}
console.log(stats);
})
复制代码
缺点:颗粒度太粗,看不出问题所在。
const SpeedMeasureWebpackPlugin = require('speed-measure-webpack-plugin')
const smp = new SpeedMesurePlugin();
const webpackConfig = smp.wrap({
plugins: [
new MyPlugin();
new MyOtherplugin()
]
})
复制代码
const {BundleAnalyzerPlugin} =require('webpack-bundle-analyzer')
module.exports = {
plugins: [
new BundleAnalyzerPlugin()
]
}
复制代码
构建完成后会在8888端口展开大小
原理:每次webpack解析一个模块,thread-loader会将他及它的依赖分配给worker线程中
use:[
{
loader:'thread-loader',
options: {
workers: 3
}
}]
复制代码
const ParalleUglifyPlugin = require('parallel-uglify-plugin')
module.exports = {
plugins: [
new ParalleUglifyPlugin({
uglifyJs:{
output: {
beautify:false,
comments:false,
},
compress:{
warnings: false,
drop_console:true,
collapse_vars:true,
reduce_vars:true
}
}
})
]
}
复制代码
plugins: [
new UglifyJsPlugin({
uglifyOptions:{},
parallel:true
})
]
复制代码
module.exports = {
optimization: {
minimizer: [
new TerserPlugin({
parrallel:4
})
]
}
}
复制代码
思路:将react, react-dom, redux, react-redux基础包和业务基础打包成一个文件。
方法:创建一个单独的配置文件,一般命名为webpack.dll.js,使用DLLPlugin进行分包,DllReferencePlugin对manifest.json引用。
const path = require('path')
const webpack = requrie('webpack')
module.exports = {
context: process.cwd(),
resolve:{
extensions:['js', 'jsx', '.json', '.less', '.css'],
modules:[__dirname, 'node_modules']
},
entry: {
library: [
'react',
'react-dom',
'redux',
'react-redux']
},
output: {
filename: '[name].dll.js',
path: path.resolve(__dirname, './build/library'),
library: '[name]'
},
plugins: [
new webpack.Dllplygin({
name: '[name]',
path: './build/library/[name].json'
})
]
}
复制代码
在webpack.config.js引入
module.exports = {
plugins: [
new webpack.DllReferencePlugin({
mainfest:require('./build/library/mainfest.json')
})
]
}
复制代码
缓存思路:
目的:尽可能的少构建模块
比如babel-laoder不解析node_modules
module.exports = {
rules: {
test: /\\.js$/,
loader: 'babel-loader',
exclude: 'node_modules'
}
}
复制代码
module.exports = {
resolve: {
alias: {
react: path.resolve(__dirname, './node_modules/react/dist/react.min.js')
},
modules: [path.resolve(__dirname, 'node_modules')],
extensions: ['js'],
mainFilelds:['main'],
}
}
复制代码
要求: 基于Node库的imagemin或者tinypngAPI
使用: 配置image-webpack-loader
return {
test: /\\.(png|svg|jpg|gif)$/,
use: [{
loader:'file-loader'
options:{
name: `${filename}img/[name]${hash}.[ext]`
}
},{
loader:'image-webpack-loader',
options: {
mojpeg: {
progressive: true,
quality: 65
},
optipng: {
enabled: false,
} ,
pngquant: {
quality: '65-90',
speed: 4
}
}
}]
}
复制代码
识别User Agent,下发不同的Polyfill
原文链接: https://juejin.cn/post/6844904136622751758