Webpack 性能优化(二)
一、使用DllPlugin(动态链接库):将网页依赖的基础模块比如rect,react-dom,vue模块抽离出来,打包到一个个单独的动态链接库中,当业务需要的导入的模块存在链接库中,不会再次打包,而是直接去取,
Webpack插件:
DllPlugin: 用于打包出一个个单独的动态链接库文件
DllReferencePlugin: 用于在主要的配置文件中引入DllPlugin插件打包好的动态链接库
const path = require(‘path’);
const DllPlugin = require(‘webpack/lib/DllPlugin’);
module.exportsc = {
entry: {
polyfill: [
‘core-js/fn/obejct/assign’,
‘core-js/fn/promise’,
‘whatwg-fetch’
]
},
output: {
path: path.join(__dirname, ‘dist’),
filename: ‘[name].dll.js’,
library: ‘dll[name]’
},
plugins: [
new DllPlugin({
name: ‘dll[name]’,
path: path.join(__dirname, ‘dis’, ‘[name].mainfest.json’)
})
]
}
plugin: [
new DllReferencePlugin({
manifest: require(’./dist/polyfill.mainfest.json’)
})
],
devtool: ‘sourse-map’
二、使用HappyPack(分解任务和管理线程)
将部分任务分解到多个进程中去并行处理
module: {
rules:[{
test: /.js$/,
//use: [‘babel-loader?cacheDirectory’],
use: ['happypack/loader?id=label'],
include: path.resolve(__dirname, 'src'),
exclude: path.resolve(__dirname, 'node_modules')
}, {
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'happyhack/loader?id=css'
]
}]
},
plugin: [
new DllReferencePlugin({
manifest: require('./dist/polyfill.mainfest.json')
}),
new HappyPack({
id: 'babel',
loader:['babel-loader?cacheDirectory'],
threadPool: happyThreadPool
}),
new HappyPack({
id: 'css',
loader:['css-loader'],
threadPool: happyThreadPool
})
],
devtool: 'sourse-map'
三、ParalleUglifyPlugin 并行压缩代码
new ParallelUglifyPlugin({
uglifyJS: {
output: {
beautify: false, //紧凑输出
comments: false //删除注释
}
}
})
四、使用自动刷新浏览器
1.自动刷新原理
(1)借助浏览器提供的接口去刷新
(2)想要开发的网页注入代理客户端代码,通过代理客户端刷新这个页面
(3)将要开发的网页装进iframe,通过刷新iframe看到最新效果
Web-dev-server默认采用的是第二种
Webpack-dev-server --inline false 采用第三种,不用给每个输出的chunk都注入代理客户端代码
五、开启模块热替换
new ParallelUglifyPlugin({
uglifyJS: {
output: {
beautify: false, //紧凑输出
comments: false //删除注释
}
}
}),
new HotModuleReplacementPlugin()
],
devServer:{
hot: true
},
六、区分环境(压缩代码)
process.env.NODE_ENV
七、CDN加速(内容分发网络,加速网络传输)
publicPath: ‘’
Web-webpack-plugin
八、Tree Shaking(针对ES6)
关闭babel自动转换功能,再通过压缩UglifyJS处理或者直接运行的时候带上 --optimize-minimize参数
{
“presets”: [
[
“env”,
{
“modules”: false
}
]
]
}
九、提取公共代码—CommonChunkPlugbin
new HotModuleReplacementPluCommonChunkPlugbingin(),
new CommonChunkPlugbin({
chunks: [‘a’, ‘b’],
name: ‘common’
})
十、分割代码按需加载(vue require)
十、Prepack(优化代码在运行时的效率)
在编译阶段预执行源码得到结果
new CommonChunkPlugbin({
chunks: [‘a’, ‘b’],
name: ‘common’
}),
new PrepackWebpackPlugin()
十一、Scope Hoisting(作用域提升, ES6)
打出来的文件更小,运行的更快
new PrepackWebpackPlugin(),
new ModuleConcatenationPlugin()