Vue首屏性能分析和优化

性能分析 借助插件 webpack-bundle-analyzer 先安装

运行

npm install webpack-bundle-analyzer –save-dev

配置

在vue.congfig.js中

配置好 BundleAnalyzerPlugin 代码如下   
 

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
    publicPath: "./",//表示打包 打相对路径
    configureWebpack:{
    plugins: [
        new BundleAnalyzerPlugin({
            //  可以是`server`,`static`或`disabled`。
            //  在`server`模式下,分析器将启动HTTP服务器来显示软件包报告。
            //  在“静态”模式下,会生成带有报告的单个HTML文件。
            //  在`disabled`模式下,你可以使用这个插件来将`generateStatsFile`设置为`true`来生成Webpack Stats JSON文件。
            analyzerMode: 'server',
            //  将在“服务器”模式下使用的主机启动HTTP服务器。
            analyzerHost: '127.0.0.1',
            //  将在“服务器”模式下使用的端口启动HTTP服务器。
            analyzerPort: 8888,
            //  路径捆绑,将在`static`模式下生成的报告文件。
            //  相对于捆绑输出目录。
            reportFilename: 'report.html',
            //  模块大小默认显示在报告中。
            //  应该是`stat`,`parsed`或者`gzip`中的一个。
            //  有关更多信息,请参见“定义”一节。
            defaultSizes: 'parsed',
            //  在默认浏览器中自动打开报告
            openAnalyzer: true,
            //  如果为true,则Webpack Stats JSON文件将在bundle输出目录中生成
            generateStatsFile: false,
            //  如果`generateStatsFile`为`true`,将会生成Webpack Stats JSON文件的名字。
            //  相对于捆绑输出目录。
            statsFilename: 'stats.json',
            //  stats.toJson()方法的选项。
            //  例如,您可以使用`source:false`选项排除统计文件中模块的来源。
            //  在这里查看更多选项:https:  //github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
            statsOptions: null,
            logLevel: 'info' // 日志级别。可以是'信息','警告','错误'或'沉默'。
        })
    ]
}
}

在启动项目 npm run serve 可以看到下面的图片 里面有每个资源的大小

优化呢   重点来了 

1使用路由懒加载

这个简单就是改变路由的写法 改成user1那种按需要引入就可以了

 {
    path: "/user",
    name: "user",
    component: User
  },
  {
    path: "/user1",
    name: "user1",
    component: ()=>import("../views/User1.vue")
  },

2使用 CDN 引入需要的库

CDN:我们打个比方 你有个房子 是两室一厅 你和你媳妇也给房 你的孩子一个房价 一天爸妈来了 住不下 我们可以去外面租一个宾馆开一个房

也可以挤一挤 挤一挤就是资源压力全部在自己家 自己家就是自己的服务器

宾馆的房子 就是cdn 专门提供资源的 当爸妈走了 也就不需要了

找到可以提供资源的cdn 推荐网址 https://jshub.com/  去里面好到自己需要的

2.1修改资源的引入方式 回到public的index.html中去 添加引入方式
 

<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"> -->
  <meta name="referrer" content="no-referrer" />
  <link rel="icon" href="<%= BASE_URL %>favicon.ico">
  <title>vue</title>
  <link href="https://libs.jshub.com/vant/2.12.12/index.css" rel="stylesheet">
  <script src="https://libs.jshub.com/vue/2.6.11/vue.runtime.min.js"></script>
  <script src="https://libs.jshub.com/vue-router/3.2.0/vue-router.min.js"></script>
  <script src="https://libs.jshub.com/vuex/3.1.3/vuex.min.js"></script>
  <script src="https://libs.jshub.com/axios/0.19.2/axios.min.js"></script>
  <script src="https://libs.jshub.com/vant/2.12.12/vant.js"></script>
  <script src="https://libs.jshub.com/echarts/4.7.0/echarts.min.js"></script>
</head>

2.2:在vue.congfig.js中修改配置 以后忽略本地使用 全部采用网络地址 注意对应规则 van:"vant" "element-ui": "ELEMENT" 需要什么插件 就配置什么插件

 externals: {
            vue: "Vue",
            vuex: "Vuex",
            "vue-router": "VueRouter",
            axios: "axios",
            echarts: "echarts",
            vant: "vant",
            "vue-i18n": "VueI18n",
        },

2.3:回到代码使用的地方 本地使用的插件 进入注释

main.js中

import Vue from 'vue'
import router from './router'
import store from './store'
// import Vant from 'vant';
// import 'vant/lib/index.css';
//  Vue.use(Vant);//整个vue项目 都可以使用vant

router/index.js中

// import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import List from "../views/List.vue"
import User from "../views/User.vue"
import Test from "../views/Test.vue";
import Detail from "../views/Detail.vue";
import Buy from "../views/Buy.vue";
import Login from "../components/mine/Login.vue";
import Register from "../components/mine/Register.vue";
import NotFound from "../views/NotFound.vue";
import  Test1 from "../views/Test1.vue";
import  Test2 from "../views/Test2.vue";
// Vue.use(VueRouter)

store/index.js中

// import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate"
import userModel from "../model/userModel";
import myshoppingcar from "./myshoppingcar"
import myaddress  from "./myaddress"
// Vue.use(Vuex)

2.4在重新启动 项目 项目能够正常运行 查看一下 加载情况 和引入地址  

看看资源加载情况

3:接着再来打包一下 npm run build  

发现里面有很多map文件

.map文件的作用:项目打包后,代码都是经过压缩加密的,如果运行时报错,输出的错误信息无法准确得知是哪里的代码报错。

有了map就可以像未加密的代码一样,准确的输出是哪一行哪一列有错。

注意:生产环境打包一般需要禁止map输出,map文件会造成项目源码泄漏

可以就行 丢弃
 

productionSourceMap: false,

 再次打包就没有map文件了

4:js还可以继续优化  安装插件 进行js的压缩处理 安装插件 需要指定版本 不然会有版本兼容问题

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

 5:配置插件的使用

const CompressionWebpackPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = ['js', 'css'];
 plugins: [
            new CompressionWebpackPlugin({
                //[file] 会被替换成原始资源。[path] 会被替换成原始资源的路径, [query] 会被替换成查询字符串。默认值是 "[path].gz[query]"。
                filename: '[path].gz[query]', // 提示compression-webpack-plugin@3.0.0的话asset改为filename
                //可以是 function(buf, callback) 或者字符串。对于字符串来说依照 zlib 的算法(或者 zopfli 的算法)。默认值是 "gzip"。
                algorithm: 'gzip',
                //所有匹配该正则的资源都会被处理。默认值是全部资源。
                test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
                //只有大小大于该值的资源会被处理。单位是 bytes。默认值是 0。
                threshold: 10240,//超过10kb直接压缩
                //只有压缩率小于这个值的资源才会被处理。默认值是 0.8。
                minRatio: 0.8
            }),

再次打包 看看打包以后的效果图

发现里面只要超过了10Kb的js 都会多一个gz的文件

当请求gzip压缩版本的js时,正确配置的Web服务器将发送js.gz,因此您可以使用gzip可以提供的最高压缩级别

6:利用服务器 就行 gzip的提速

在Nginx的服务器中打开 C:\Users\15871\Desktop\nginx-1.18.0\conf找到nginx.conf 进行配置

 # gzip config
        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]\.";
 
    root /usr/share/nginx/html;

全部的配置如下 包括了反向代理 

#user  nobody;
worker_processes  1;
 
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
#pid        logs/nginx.pid;
 
 
events {
    worker_connections  1024;
}
 
 
http {
    include       mime.types;
    default_type  application/octet-stream;
 
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
 
    #access_log  logs/access.log  main;
 
    sendfile        on;
    #tcp_nopush     on;
 
    #keepalive_timeout  0;
    keepalive_timeout  65;
 
 
    server {
        listen       9876;
 
        # gzip config
        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]\.";
 
    root /usr/share/nginx/html;
 
        server_name  localhost;
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
location / {
root html;
index index.html index.htm;
}
 
	
 location	/api/ {
   	 proxy_pass	http://localhost:3000/;
	}
 location	/api2/ {
   	 proxy_pass	http://localhost:3006/;
	}
 location	/self/ {
   	 proxy_pass	http://192.168.61.174:6789/;
	}
 
        #error_page  404              /404.html;
 
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
 
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
 
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
 
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
 
 
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
 
 
    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;
 
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
 
    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;
 
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
 
}

 7:最后打包注释掉 性能优化的BundleAnalyzerPlugin

 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值