vue-cli3.0 打包优化实践

3,730 阅读3分钟

vue-cli3.0 打包优化实践

  1. 配置 gzip 压缩,打出来一个待 gzip 后缀的文件
  2. webpack-bundle-analyzer 分析
  3. webpack splitChunks, 提取出来的通用 'echarts', 'moment', 'element-ui', 'xlsx'等
  4. momentjs 优化
  5. lodash 优化
  6. 小图片压缩成 base64 格式
  7. xlsx 改为 xlsx.mini.min
  8. nginx http1.1 改为 http2.0
  9. SEO 优化
  10. 不经常更新模块抽离(待更新)

优化后的分析图-地址

优化前后对比图

parsed

优化前大小    优化后大小
2.7MB --> 2.11MB


gzip

优化前大小    优化后大小
882.15KB --> 685.23KB


Lighthouse

1. 配置 gzip 压缩,打出来一个待 gzip 后缀的文件

$ npm i compression-webpack-plugin -D
const CompressionWebpackPlugin = require('compression-webpack-plugin');
module.exports = {
    configureWebpack: config => {
        if (process.env.NODE_ENV === 'production') {
            config.plugins.push(
                ...[
                    new CompressionWebpackPlugin({
                        filename: '[path].gz[query]',
                        algorithm: 'gzip',
                        test: /\.(js|css|html|svg)$/i,
                        threshold: 2048,
                        minRatio: 0.8
                    })
                ]
            );
        }
    }
};

2. webpack-bundle-analyzer 分析包

$ npm i webpack-bundle-analyzer -D

module.exports = {
    chainWebpack: config => {
        if (process.env.NODE_ENV === 'production') {
            // 启动时动态创建一个html:http://localhost:8888/report.html
            // config.plugin('webpack-bundle-analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin);
            // 生成一个静态html,report.html
            config.plugin('webpack-report').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, [
                {
                    analyzerMode: 'static'
                }
            ]);
        }
    }
};

3. webpack splitChunks, 提取出来的通用 'echarts', 'moment', 'element-ui', 'xlsx'等

// ['echarts', 'moment', 'element-ui', 'xlsx', 'chunk-vendors', 'chunk-common', 'index']
module.exports = {
    pages: {
        index: {
            // ...
            // 在这个页面中包含的块,默认情况下会包含
            // 提取出来的通用 chunk 和 vendor chunk。
            chunks: ['echarts', 'moment', 'element-ui', 'xlsx', 'chunk-vendors', 'chunk-common', 'index']
        },

        chainWebpack: config => {
            if (process.env.NODE_ENV === 'production') {
                // vue-cli3.x+默认配置
                // config.optimization.splitChunks({
                //     chunks: 'async',
                //     minSize: 30000,
                //     maxSize: 0,
                //     minChunks: 1,
                //     maxAsyncRequests: 6,
                //     maxInitialRequests: 4,
                //     automaticNameDelimiter: '~',
                //     cacheGroups: {
                //         vendors: {
                //             name: 'chunk-vendors',
                //             test: /[\\/]node_modules[\\/]/,
                //             priority: -10,
                //             chunks: 'initial'
                //         },
                //         common: {
                //             name: 'chunk-common',
                //             minChunks: 2,
                //             priority: -20,
                //             chunks: 'initial',
                //             reuseExistingChunk: true
                //         }
                //     }
                // });
                config.optimization.splitChunks({
                    chunks: 'async',
                    minSize: 1024 * 10, // 30000,
                    maxSize: 0,
                    minChunks: 1,
                    maxAsyncRequests: 6,
                    maxInitialRequests: 4,
                    automaticNameDelimiter: '~',
                    cacheGroups: {
                        // 链接:https://juejin.cn/post/6844904105555525640
                        echarts: {
                            name: 'echarts',
                            test: /[\\/]node_modules[\\/]echarts[\\/]/,
                            minSize: 0,
                            minChunks: 1,
                            reuseExistingChunk: true,
                            chunks: 'all'
                        },
                        moment: {
                            name: 'moment',
                            test: /[\\/]node_modules[\\/]moment[\\/]/,
                            minSize: 0,
                            minChunks: 1,
                            reuseExistingChunk: true,
                            chunks: 'all'
                        },
                        'element-ui': {
                            name: 'element-ui',
                            test: /[\\/]node_modules[\\/]element-ui[\\/]/,
                            minSize: 0,
                            minChunks: 1,
                            reuseExistingChunk: true,
                            chunks: 'all'
                        },
                        xlsx: {
                            name: 'xlsx',
                            test: /[\\/]node_modules[\\/]xlsx[\\/]/,
                            minSize: 0,
                            minChunks: 1,
                            reuseExistingChunk: true,
                            chunks: 'all'
                        },

                        vendors: {
                            name: 'chunk-vendors',
                            test: /[\\/]node_modules[\\/]/,
                            priority: -10,
                            chunks: 'initial'
                        },
                        common: {
                            name: 'chunk-common',
                            minChunks: 2,
                            priority: -20,
                            chunks: 'initial',
                            reuseExistingChunk: true
                        }
                    }
                });
            }
        }
    }
}

4. momentjs 优化

  • 方案 1:只打包使用的文件(目前用的时这个)

vue.config.js

module.exports = {
    configureWebpack: config => {
        config.plugins.push(
            ...[
                // 链接:https://juejin.cn/post/6844904105555525640
                new webpack.ContextReplacementPlugin(
                    /moment[/\\]locale$/, // 这个参数表明了我们要改变的打包上下文
                    /zh-cn/ // 这个参数表示我们只想打包这个正则匹配的文件
                )
            ]
        );
    }
};
  • 方案 2:使用 dayjs 替代 moment,代码不用变,把 lodash 配置别名为 dayjs

知乎上的文章: zhuanlan.zhihu.com/p/61031739?…

module.exports = {
    chainWebpack: config => {
        config.resolve.alias
        // set第一个参数:设置的别名,第二个参数:真实的名称(默认都是从node_modules中读取
        .set('moment','dayjs'));
        }
};

-   方案 3: ...

5. lodash 优化

$ npm i lodash-webpack-plugin babel-plugin-lodash -D

babel.config.js

module.exports = {
    presets: ['@vue/app'],
    plugins: [
        'lodash',
        [
            'component',
            {
                libraryName: 'element-ui',
                styleLibraryName: 'theme-chalk'
            }
        ]
    ]
};

vue.config.js

const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

module.exports = {
    configureWebpack: config => {
        config.plugins.push(
            ...[
                new LodashModuleReplacementPlugin(),
                // 链接:https://juejin.cn/post/6844904105555525640
                new webpack.ContextReplacementPlugin(
                    /moment[/\\]locale$/, // 这个参数表明了我们要改变的打包上下文
                    /zh-cn/ // 这个参数表示我们只想打包这个正则匹配的文件
                )
            ]
        );
    }
};

6. 小图片压缩成 base64 格式

module.exports = {
    chainWebpack: config => {
        // 10kb以内的图片会被打包成内联元素
        config.module
            .rule('images')
            .use('url-loader')
            .loader('url-loader')
            .tap(options => Object.assign(options, {limit: 10240}));
    }
};

7. xlsx 改为 xlsx.mini.min

把所有

import XLSX from 'xlsx';

改为以下的方式引入

import XLSX from 'xlsx/dist/xlsx.mini.min.js';

8. http1.1升级http2.0

注意的点:

1. nginx version 1.9.4 以上
2. 当前配置http2基于https协议

nginx配置文件 nginx.conf

	# http转https
    server {
        listen 80;
        server_name yourdomain.com; #需要将yourdomain.com替换成证书绑定的域名。
        rewrite ^(.*) https://$server_name$1 permanent; #将所有HTTP请求通过rewrite指令重定向到HTTPS。
    }

    #以下属性中,以ssl开头的属性表示与证书配置有关。
    server {
        # 开启gzip
        gzip on;

        # 启用gzip压缩的最小文件,小于设置值的文件将不会压缩
        gzip_min_length 1k;

        # gzip 压缩级别,1-9,数字越大压缩的越好,也越占用CPU时间,后面会有详细说明
        gzip_comp_level 9;

        # 进行压缩的文件类型。javascript有多种形式。其中的值可以在 mime.types 文件中找到。
        gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png application/vnd.ms-fontobject font/ttf font/opentype font/x-woff image/svg+xml;

        # 是否在http header中添加Vary: Accept-Encoding,建议开启
        gzip_vary on;

        # 禁用IE 6 gzip
        gzip_disable "MSIE [1-6]\.";

        # 设置压缩所需要的缓冲区大小
        gzip_buffers 32 4k;

        # 设置gzip压缩针对的HTTP协议版本
        gzip_http_version 1.1;
		
        # 注意这里http2
        listen 443 ssl http2;
        #配置HTTPS的默认访问端口为443。
        #如果未在此处配置HTTPS的默认访问端口,可能会造成Nginx无法启动。
        #如果您使用Nginx 1.15.0及以上版本,请使用listen 443 ssl代替listen 443和ssl on。
        server_name yourdomain.com; #需要将yourdomain.com替换成证书绑定的域名。
        root html;
        index index.html index.htm;
        ssl_certificate cert/cert-file-name.pem;  #需要将cert-file-name.pem替换成已上传的证书文件的名称。
        ssl_certificate_key cert/cert-file-name.com.key; #需要将cert-file-name.key替换成已上传的证书密钥文件的名称。
        ssl_session_timeout 5m;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
        #表示使用的加密套件的类型。
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #表示使用的TLS协议的类型。
        ssl_prefer_server_ciphers on;
        # location / {
        #     root html;  #站点目录。
        #     index index.html index.htm;
        # }

        location / {
        	# 反向代理
            proxy_pass http://127.0.0.1:8090;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

http2.0 network 效果

http2

9. SEO 优化

<meta name="description" content="vue,element-ui,nodejs,express,nginx全栈管理后台项目" />

10. 不经常更新模块抽离(待更新)

待更新