使用gzip打包vue项目,减少打包文件的体积,减少首页渲染的时间

项目打包好部署到服务器上,首页加载时间需要7秒以上,这肯定是不友好的,看了看,是因为app.css、vendor.js文件居然达到了2M以上,造成了加载时间过长,开始考虑优化打包

1、首先考虑到能不能用cdn引入资源文件,小众第三方插件不是很敢使用cdn引入,怕因为线上崩溃了,项目跟着一起完蛋,所以就引入了一些比较大一点的第三方插件
以vue-cli3项目为例子(vue-cli3一下版本可能写法不一样,网上一搜一大把)

vue.config.js文件

module.exports = {
    chainWebpack: config => {
        if (process.env.NODE_ENV === 'production') {
            // #region 忽略生成环境打包的文件
            var externals = {
                'vue': 'Vue',
                'axios': 'axios',
                'element-ui': 'ELEMENT',
                'vue-router': 'VueRouter',
                'vuex': 'Vuex',
                'echarts': 'echarts'
            }
            config.externals(externals)

            // 在html文件中引入相关CDN
            const cdn = {
                css: [
                    // element-ui css
                    'https://cdn.bootcss.com/element-ui/2.13.0/theme-chalk/index.css'
                ],
                js: [
                    // vue
                    'https://cdn.staticfile.org/vue/2.5.22/vue.min.js',
                    // vue-router
                    'https://cdn.staticfile.org/vue-router/3.0.2/vue-router.min.js',
                    // vuex
                    'https://cdn.staticfile.org/vuex/3.1.0/vuex.min.js',
                    // axios
                    'https://cdn.staticfile.org/axios/0.19.0-beta.1/axios.min.js',
                    // element-ui js
                    'https://cdn.bootcss.com/element-ui/2.13.0/index.js',
                    //echarts
                    'https://cdn.bootcss.com/echarts/4.6.0/echarts-en.common.js'
                ]
            }
            config.plugin('html')
                .tap(args => {
                    args[0].cdn = cdn
                    return args
                })
        }
    },

    //...省略的其它代码

}

index.html文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <% if (process.env.NODE_ENV === 'production') { %>

      <% for(var css of htmlWebpackPlugin.options.cdn.css) { %>
        <link href="<%=css%>" rel="preload" as="style">
        <link rel="stylesheet" href="<%=css%>" as="style">
      <% } %>
      <% for(var js of htmlWebpackPlugin.options.cdn.js) { %>
        <link href="<%=js%>" rel="preload" as="script">
        <script src="<%=js%>"></script>
      <% } %>

    <% } %>
    <title>bxxt</title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but bxxt doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

main.js把之前引入的代码注释掉

// elemntui组件库,打包部署采用cdn需注释掉
// import ElementUI from 'element-ui';
// import 'element-ui/lib/theme-chalk/index.css';
// import 'element-ui/lib/theme-chalk/display.css';
// Vue.use(ElementUI);

最后进行打包

但是使用这种方法打包后的文件体积会减少,但是怎么说呢,减少了0.xM,首页效果还是不明显,而且后面在刷页面的时候会偶发找不到cdn资源,这样就不好了,所以考虑用第二种方法

2、使用gzip打包

安装插件:这里安装这个插件要注意版本,我下的是1.1.12版本,更高版本会报错,所以如果报错了,记得安装1.1.12版本的compression-webpack-plugin

npm install compression-webpack-plugin@1.1.12 --save-dev

vue.config.js文件中进行配置

const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
        plugins: [
            new CompressionPlugin({
                algorithm: 'gzip', // 使用gzip压缩
                test: /\.js$|\.html$|\.css$/, // 匹配文件名
                filename: '[path].gz[query]', // 压缩后的文件名(保持原文件名,后缀加.gz)
                minRatio: 1, // 压缩率小于1才会压缩
                threshold: 10240, // 对超过10k的数据压缩
                deleteOriginalAssets: false, // 是否删除未压缩的源文件,谨慎设置,如果希望提供非gzip的资源,可不设置或者设置为false(比如删除打包后的gz后还可以加载到原始资源文件)
            }),
        ],
    },
};

这里前端配置工作结束,还需要后端配置一个ngix

理由:浏览器请求xx.js/css等文件时,服务器返回对应的xxx.js.gz文件,所以还需要在服务器配置一个属性,以期望它能正常返回我们需要的gz文件。

nginx.conf文件

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    gzip_static on;

    server {
        listen       8462;
        server_name  localhost;

        location / {
            root   dist;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

}

果然,文件小了5-6倍,文件体积减小还是非常明显的,首页1-2秒就加载出来了

打包优化over!!

更好的方式请评论出来,一起学习~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值