vue项目优化

一、项目优化

1.关闭productionSourceMap

首先,由于最新版的脚手架不自带配置文件了,先在根目录新建vue.config.js文件,关闭productionSourceMap,在vue.config.js中写入如下内容

module.exports = {
    productionSourceMap: false
}

2、开启Gzip压缩

安装插件compression-webpack-plugin,打开代码压缩,npm install --save-dev compression-webpack-plugin,现在的vue.config.js代码如下,但是,需要注意的是,服务器上nginx也必须开启gzip才能生效

// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';

// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin')

module.exports = {
    productionSourceMap: false,
    configureWebpack: config => {
        // 生产环境相关配置
        if (isProduction) {
            //gzip压缩
            const productionGzipExtensions = ['html', 'js', 'css']
            config.plugins.push(
                new CompressionWebpackPlugin({
                    filename: '[path].gz[query]',
                    algorithm: 'gzip',
                    test: new RegExp(
                        '\\.(' + productionGzipExtensions.join('|') + ')$'
                    ),
                    threshold: 10240, // 只有大小大于该值的资源会被处理 10240
                    minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
                    deleteOriginalAssets: false // 删除原文件
                })
            )
        }
    }
}

打开nginx文件夹下的nginx.conf文件,在http模块中写入以下内容

# 开启gzip
gzip on;

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

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

# 进行压缩的文件类型。javascript有多种形式,后面的图片压缩不需要的可以自行删除
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;

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

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

然后输入命令nginx -s reload重启nginx服务
如果后端nginx开启了gzip,可以从network中的Content-Encoding中看到gzip
在这里插入图片描述

3.开启CDN加速(建议选配,CDN虽然速度快,但没有本地打包稳定)

将使用的插件使用cdn链接,并且配置webpack将使用CDN的插件不进行打包,别忘记还要再index.html中引入js以及css

// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';

// 本地环境是否需要使用cdn
const devNeedCdn = false

// cdn链接
const cdn = {
    // cdn:模块名称和模块作用域命名(对应window里面挂载的变量名称)
    externals: {
        vue: 'Vue',
        vuex: 'Vuex',
        'vue-router': 'VueRouter',
        'marked': 'marked',
        'highlight.js': 'hljs',
        'nprogress': 'NProgress',
        'axios': 'axios'
    },
    // cdn的css链接
    css: [
        'https://cdn.bootcss.com/nprogress/0.2.0/nprogress.min.css'
    ],
    // cdn的js链接
    js: [
        'https://cdn.bootcss.com/vue/2.6.10/vue.min.js',
        'https://cdn.bootcss.com/vuex/3.1.2/vuex.min.js',
        'https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js',
        'https://cdn.bootcss.com/marked/0.8.0/marked.min.js',
        'https://cdn.bootcss.com/highlight.js/9.18.1/highlight.min.js',
        'https://cdn.bootcss.com/nprogress/0.2.0/nprogress.min.js',
        'https://cdn.bootcss.com/axios/0.19.2/axios.min.js'
    ]
}

module.exports = {
    chainWebpack: config => {
        // ============注入cdn start============
        config.plugin('html').tap(args => {
            // 生产环境或本地需要cdn时,才注入cdn
            if (isProduction || devNeedCdn) args[0].cdn = cdn
            return args
        })
        // ============注入cdn start============
    },
    configureWebpack: config => {
        // 用cdn方式引入,则构建时要忽略相关资源
        if (isProduction || devNeedCdn) config.externals = cdn.externals
    }
}

接下来,在index.html中引入使用了CDN的链接

<!DOCTYPE html>
<html lang="en" style="width: 100%;height: 100%;">
  <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">

    <!-- 使用CDN的CSS文件 -->
    <% for (var i in htmlWebpackPlugin.options.cdn &&
    htmlWebpackPlugin.options.cdn.css) { %>
    <link
            href="<%= htmlWebpackPlugin.options.cdn.css[i] %>"
            rel="stylesheet"
    />
    <% } %>
    <!-- 使用CDN的CSS文件 -->

    <title>CoolDream</title>
  </head>
  <body style="width: 100%;height: 100%;">
    <noscript>
      <strong>We're sorry but blog doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->

    <!-- 使用CDN的JS文件 -->
    <% for (var i in htmlWebpackPlugin.options.cdn &&
    htmlWebpackPlugin.options.cdn.js) { %>
    <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script>
    <% } %>
    <!-- 使用CDN的JS文件 -->

  </body>
</html>

打包后抛到服务器上,打开开发者工具的network,如果看到http请求cdn,那么就代表配置成功了,如图所示
在这里插入图片描述

4.代码压缩

先安装插件npm i -D uglifyjs-webpack-plugin
然后在最上方引入依赖

// 代码压缩
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

在configureWebpack模块中引入代码压缩

// 代码压缩
config.plugins.push(
    new UglifyJsPlugin({
        uglifyOptions: {
            //生产环境自动删除console
            compress: {
                drop_debugger: true,
                drop_console: true,
                pure_funcs: ['console.log']
            }
        },
        sourceMap: false,
        parallel: true
    })
)

5.公共代码抽离,写在configureWebpack模块中

// 公共代码抽离
config.optimization = {
    splitChunks: {
        cacheGroups: {
            vendor: {
                chunks: 'all',
                test: /node_modules/,
                name: 'vendor',
                minChunks: 1,
                maxInitialRequests: 5,
                minSize: 0,
                priority: 100
            },
            common: {
                chunks: 'all',
                test: /[\\/]src[\\/]js[\\/]/,
                name: 'common',
                minChunks: 2,
                maxInitialRequests: 5,
                minSize: 0,
                priority: 60
            },
            styles: {
                name: 'styles',
                test: /\.(sa|sc|c)ss$/,
                chunks: 'all',
                enforce: true
            },
            runtimeChunk: {
                name: 'manifest'
            }
        }
    }
}

6.图片压缩()

1.使用图片压缩插件
先安装插件npm install image-webpack-loader --save-dev
在chainWebpack中新增以下代码

// ============压缩图片 start============
config.module
    .rule('images')
    .use('image-webpack-loader')
    .loader('image-webpack-loader')
    .options({ bypassOnDebug: true })
    .end()
// ============压缩图片 end============

7.首屏骨架屏优化(选配,看自己实际需要吧)

1.安装插件

npm install vue-skeleton-webpack-plugin --save

2.新建骨架屏文件
在src下新建Skeleton文件夹,其中新建index.js以及index.vue,在其中写入以下内容,其中,骨架屏的

index.vue页面样式请自行编辑

//index.js
import Vue from 'vue'
// 创建的骨架屏 Vue 实例
import skeleton from './index.vue';

export default new Vue({
    components: {
        skeleton
    },
    template: '<skeleton />'
});
//index.vue
<template>
    <div class="skeleton-box">
        loading
    </div>
</template>

<script lang="ts">
    import {Vue,Component} from "vue-property-decorator";

    @Component({
        name:'Skeleton'
    })
    export default class Skeleton extends Vue{

    }
</script>

<style lang="stylus" scoped>
.skeleton-box{
    font-size 24px
    display flex
    align-items center
    justify-content center
    width 100vh
    height 100vh
}
</style>

3.在vue.config.js中配置骨架屏
在vue.config.js中写入以下内容

//骨架屏渲染
const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin')

//path引入
const path = require('path')

//configureWebpack模块中写入内容
// 骨架屏渲染
config.plugins.push(
    new SkeletonWebpackPlugin({
        webpackConfig: {
            entry: {
                app: path.join(__dirname,'./src/components/Skeleton/index.js')
            }
        }
    })
)

所以,最终的配置文件如下

// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';

// 代码压缩
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin')

//骨架屏渲染
const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin')

//path引入
const path = require('path')

// 本地环境是否需要使用cdn
const devNeedCdn = false

// cdn链接
const cdn = {
    // cdn:模块名称和模块作用域命名(对应window里面挂载的变量名称)
    externals: {
        vue: 'Vue',
        vuex: 'Vuex',
        'vue-router': 'VueRouter',
        'marked': 'marked',
        'highlight.js': 'hljs',
        'nprogress': 'NProgress',
        'axios': 'axios'
    },
    // cdn的css链接
    css: [
        'https://cdn.bootcss.com/nprogress/0.2.0/nprogress.min.css'
    ],
    // cdn的js链接
    js: [
        'https://cdn.bootcss.com/vue/2.6.10/vue.min.js',
        'https://cdn.bootcss.com/vuex/3.1.2/vuex.min.js',
        'https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js',
        'https://cdn.bootcss.com/marked/0.8.0/marked.min.js',
        'https://cdn.bootcss.com/highlight.js/9.18.1/highlight.min.js',
        'https://cdn.bootcss.com/nprogress/0.2.0/nprogress.min.js',
        'https://cdn.bootcss.com/axios/0.19.2/axios.min.js'
    ]
}

module.exports = {
    productionSourceMap: false,
    chainWebpack: config => {
        // ============注入cdn start============
        config.plugin('html').tap(args => {
            // 生产环境或本地需要cdn时,才注入cdn
            if (isProduction || devNeedCdn) args[0].cdn = cdn
            return args
        })
        // ============注入cdn start============

        // ============压缩图片 start============
        config.module
            .rule('images')
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({ bypassOnDebug: true })
            .end()
        // ============压缩图片 end============
    },
    configureWebpack: config => {
        // 用cdn方式引入,则构建时要忽略相关资源
        if (isProduction || devNeedCdn) config.externals = cdn.externals

        // 生产环境相关配置
        if (isProduction) {
            //gzip压缩
            const productionGzipExtensions = ['html', 'js', 'css']
            config.plugins.push(
                new CompressionWebpackPlugin({
                    filename: '[path].gz[query]',
                    algorithm: 'gzip',
                    test: new RegExp(
                        '\\.(' + productionGzipExtensions.join('|') + ')$'
                    ),
                    threshold: 10240, // 只有大小大于该值的资源会被处理 10240
                    minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
                    deleteOriginalAssets: false // 删除原文件
                })
            )

            // 代码压缩
            config.plugins.push(
                new UglifyJsPlugin({
                    uglifyOptions: {
                        //生产环境自动删除console
                        compress: {
                            drop_debugger: true,
                            drop_console: true,
                            pure_funcs: ['console.log']
                        }
                    },
                    sourceMap: false,
                    parallel: true
                })
            )
        }

        // 骨架屏渲染
        config.plugins.push(
            new SkeletonWebpackPlugin({
                webpackConfig: {
                    entry: {
                        app: path.join(__dirname,'./src/components/Skeleton/index.js')
                    }
                }
            })
        )

        // 公共代码抽离
        config.optimization = {
            splitChunks: {
                cacheGroups: {
                    vendor: {
                        chunks: 'all',
                        test: /node_modules/,
                        name: 'vendor',
                        minChunks: 1,
                        maxInitialRequests: 5,
                        minSize: 0,
                        priority: 100
                    },
                    common: {
                        chunks: 'all',
                        test: /[\\/]src[\\/]js[\\/]/,
                        name: 'common',
                        minChunks: 2,
                        maxInitialRequests: 5,
                        minSize: 0,
                        priority: 60
                    },
                    styles: {
                        name: 'styles',
                        test: /\.(sa|sc|c)ss$/,
                        chunks: 'all',
                        enforce: true
                    },
                    runtimeChunk: {
                        name: 'manifest'
                    }
                }
            }
        }
    }
}

8.nginx配置缓存
同样也可以提高网站的访问速度(虽然这点有点偏离前端打包主题了,但是对于自己独立开发个人博客网站的前端来说还是非常有用的!)在nginx.conf的http模块中写入一下内容

 # 设置缓存路径并且使用一块最大100M的共享内存,用于硬盘上的文件索引,包括文件名和请求次数,每个文件在1天内若不活跃(无请求)则从硬盘上淘汰,硬盘缓存最大10G,满了则根据LRU算法自动清除缓存。
proxy_cache_path /var/cache/nginx/cache levels=1:2 keys_zone=imgcache:100m inactive=1d max_size=10g;

然后在nginx.conf的serve模块中写入一下内容,保存配置,nginx -s reload重启服务即可看到效果

location ~* ^.+\.(css|js|ico|gif|jpg|jpeg|png)$ {
 log_not_found off;
 # 关闭日志
 access_log off;
 # 缓存时间7天
 expires 7d;
 # 源服务器
 proxy_pass http://localhost:8888;
 # 指定上面设置的缓存区域
 proxy_cache imgcache;
 # 缓存过期管理
 proxy_cache_valid 200 302 1d;
 proxy_cache_valid 404 10m;
 proxy_cache_valid any 1h;
 proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
 }

原文链接:https://juejin.im/post/6844904071896236040

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值