首先通过npm run analyze 查看打包后的文件进行观察,哪些包的体积大,然后分解开
体积较大的文件:echarts、wangeditor、antd、moment.js
package.json 文件配置
.umirc.ts配置文件
1. 分包配置
通过 webpack-chain 的 API 修改 webpack 配置。
chunks: process.env.NODE_ENV === 'production' ? ['echarts', 'antdesigns', 'vendors', 'commons', 'umi'] : ['umi'],chainWebpack: function (config: any) {if (process.env.NODE_ENV === 'production') {config.merge({optimization: {minimize: true,splitChunks: {chunks: 'all', //async异步代码分割 initial同步代码分割 all同步异步分割都开启automaticNameDelimiter: '.',name: true, // 缓存组里面的filename生效,覆盖默认命名minSize: 30000, // 引入的文件大于30kb才进行分割//maxSize: 50000, // 50kb,尝试将大于50kb的文件拆分成n个50kb的文件minChunks: 1, // 模块至少使用次数// maxAsyncRequests: 5, // 同时加载的模块数量最多是5个,只分割出同时引入的前5个文件// maxInitialRequests: 3, // 首页加载的时候引入的文件最多3个 cacheGroups: {echarts: {name: 'echarts',chunks: 'all',test: /[\\/]node_modules[\\/](echarts)/,priority: 10,enforce: true,},antdesigns: {name: 'antdesigns',chunks: 'all',test: /[\\/]node_modules[\\/](@antv|antd|@ant-design)/,priority: 10,},vendors: {name: 'vendors',chunks: 'all',test: /[\\/]node_modules[\\/](lodash-es|moment|react|dva)/,priority: 10,},commons: {name: 'commons',chunks: 'all',// minChunks: 2,priority: 1,enforce: true,},},},},})},
2. Gzip压缩
chainWebpack: function (config: any) {//gzip压缩config.plugin('compression-webpack-plugin').use(CompressionPlugin, [{test: /.(js|html|css)$/i, //匹配文件名threshold: 10240, //对超过10k的数据压缩deleteOriginalAssets: false, //不删除源文件},])}
3. 组件懒加载
需要开启mfsu,umi 版本 “umi”: “^3.5.41”,
mfsu: {},webpack5: {},dynamicImport: {// @ 默认指到 src 目录loading: '@/pages/Loading',},
4. moment.js 语言包剔除
chainWebpack: function (config: any) {config.plugin('moment-locale').use(require('webpack').ContextReplacementPlugin, [/moment[\/\\]locale$/, /en|zh-cn/])},
5.lodash替换方案lodash-es
“lodash-es”: “^4.17.21”,
调整后