Document

前端项目时因chunk-vendors过大导致首屏加载太慢的优化

前端项目时因chunk-vendors过大导致首屏加载太慢的优化

因app首页加载不流畅,于是去检查首页加载项的耗时,最终发现是前端加载时js文件太大,导致首页加载太慢,于是选择了以下方案进行优化。

一、安装compression-webpack-plugin插件。前端将文件打包成.gz文件,然后通过nginx的配置,让浏览器直接解析.gz文件,可以大大提升文件加载的速度。

1.npm使用下面命令安装

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

2.yarn使用下面命令安装

yarn add compression-webpack-plugin --save-dev

二、接下来要去修改vue的配置文件 vue.config.js

const path = require('path');

const webpack = require('webpack')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css']
const isProduction = process.env.NODE_ENV === 'production'



module.exports = {
  publicPath:'/appShare/',
  productionSourceMap: false,
  configureWebpack:{
    resolve:{
      alias:{
        '@':path.resolve(__dirname, './src'),
        '@i':path.resolve(__dirname, './src/assets'),
      } 
    },
    plugins: [
      // Ignore all locale files of moment.js
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      
      // 配置compression-webpack-plugin压缩
      new CompressionWebpackPlugin({
        algorithm: 'gzip',
        test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
        threshold: 10240,
        minRatio: 0.8
      }),
      new webpack.optimize.LimitChunkCountPlugin({
        maxChunks: 5, 
        minChunkSize: 100
      })
    ]

  },

 

三、nginx配置

server{
    listen 8087;
    server_name localhost;

    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 9;
    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;
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.";

    location /appShare {
       client_max_body_size    10m;
       root /home/test/webIndex/appShare;
       try_files $uri $uri/ /appShare/index.html;
       index index.htm index.html;
    }

}

四、打包后对比结果很明显,原来1.3M的js文件被压缩到了351k,前端加载的速度也提升的很多。

[root@localhost js]# ll -h 
总用量 1.9M
-rw-r--r-- 1 root root 1.3M 10月 25 13:56 answer.1e6b29ba.js
-rw-r--r-- 1 root root 351K 10月 25 13:56 answer.1e6b29ba.js.gz
-rw-r--r-- 1 root root  49K 10月 25 13:56 app.319e43e7.js
-rw-r--r-- 1 root root  18K 10月 25 13:56 app.319e43e7.js.gz
-rw-r--r-- 1 root root  21K 10月 25 13:56 list.898721c9.js
-rw-r--r-- 1 root root 5.0K 10月 25 13:56 list.898721c9.js.gz
-rw-r--r-- 1 root root  45K 10月 25 13:56 qa.d8599e38.js
-rw-r--r-- 1 root root  14K 10月 25 13:56 qa.d8599e38.js.gz
-rw-r--r-- 1 root root  45K 10月 25 13:56 shareBottle2.4ceeca4d.js
-rw-r--r-- 1 root root  14K 10月 25 13:56 shareBottle2.4ceeca4d.js.gz
[root@localhost js]#

 

posted @ 2021-07-16 08:54  李宗光  阅读(2846)  评论(0编辑  收藏  举报