配置打包体积分析与耗时分析
1 | yarn add webpack-bundle-analyzer speed-measure-webpack-plugin |
webpakc.config.js
1 | // 可视化打包 |
根据体积分析与耗时插件的分析结果在针对优化
配置 externals
webpakc.config.js
1 | module.exports = { |
- 项目中可根据环境针对配置
配置 Tree Shaking
package.json
1 | { |
webpack.config.js
1 | module.exports = { |
代码
1 | export default /*#__PURE__*/ () => { |
- 开启 Tree Shaking 后
import './index.less'
将不会被打包…
解决方案
package.json
1 | { |
- 添加副作用
sideEffects
后,下面情况样式失效1
2
3
4
5import './index.less'
export { default as CompontentA } from './CompontentA'
export { CompontentB } from './Compontent'; // 图片压缩
多线程打包
HappyPack (不推荐,不再维护)
1 | npm install --save-dev happypack |
webpack.config.js
1 | const HappyPack = require('happypack'); |
thread-loader
1 | npm install --save-dev thread-loader |
webpack.config.js
1 | module.exports = { |
缓存已编译过的文件
webpack4
webpack.config.js
1 | module.exports = { |
webpack5
- 开发环境默认开启缓存,生产模式禁用,缓存默认是在内存里。可以对 cache 进行设置
文件缓存:
webpack.config.js
1 | module.exports = { |
缓存淘汰策略:文件缓存存储在 node_ modules/.cache/webpack,最大 500 MB, 缓存时常两个星期,旧的缓存先淘汰
DllPlugin
该插件可以将特定的类库提前打包然后引入,这种方式可以极大的减少类库的打包次数,只有当类库有更新版本时才会重新打包,并且也实现了将公共代码抽离成单独文件的优化方案