项目开发流程介绍(项目优化)

因为是移动端项目,所以选择了vue+vant-ui。vue它是一个 MVVM 框架,有一套脚手架可以便于我们高效开发,生态已经非常的强大,在 github 上的 star已经10W+,其次有各种各样的第三方库。vant就是目前业界主流的移动端组件库之一,是一个轻量的组件库,比较符合国人的审美

1.首先通过vue的脚手架创建项目,需要配置多环境变量,项目要经三个阶段,开发阶段、测试阶段、最后是发布上线

package.json 里的 scripts 配置 serve stage build,通过 --mode xxx 来执行不同环境

  "scripts": {
    "serve": "vue-cli-service serve",
    "stage": "vue-cli-service build --mode staging",
    "build": "vue-cli-service build"
  },
  • 通过 npm run serve 启动本地 , 执行 development

  • 通过 npm run stage 打包测试 , 执行 staging

  • 通过 npm run build 打包正式 , 执行 production

    在根目录创三个文件:

  • .env.development 本地开发环境配置

NODE_ENV='development'
# must start with VUE_APP_
VUE_APP_ENV = 'development'
  • .env.staging 测试环境配置
NODE_ENV='production'
# must start with VUE_APP_
VUE_APP_ENV = 'staging'
  • .env.production 正式环境配置
 NODE_ENV='production'
# must start with VUE_APP_
VUE_APP_ENV = 'production'

再src目录下创建config文件夹,创建对应的js文件
env.development.js

// 本地环境配置
module.exports = {
  title: 'vue-h5-template',
  baseUrl: 'http://localhost:9020', // 项目地址
  baseApi: '/', // 本地api请求地址,注意:如果你使用了代理,请设置成'/'
  APPID: 'xxx',
  APPSECRET: 'xxx',
  $cdn: 'https://gimg2.baidu.com'
}

env.staging.js

module.exports = {
  title: 'vue-h5-template',
  baseUrl: 'https://test.xxx.com', // 测试项目地址
  baseApi: 'https://test.xxx.com/api', // 测试api请求地址
  APPID: 'xxx',
  APPSECRET: 'xxx',
  $cdn: 'https://www.sunniejs.cn/static'
}

env.production.js

// 正式
module.exports = {
  title: 'vue-h5-template',
  baseUrl: 'http://localhost:9020', // 正式项目地址
  baseApi: '/', // 正式api请求地址
  APPID: 'xxx',
  APPSECRET: 'xxx',
  $cdn: 'https://www.sunniejs.cn/static'
}

再创建一个index.js

// 根据环境引入不同配置 process.env.VUE_APP_ENV
const environment = process.env.VUE_APP_ENV || 'production'
const config = require('./env.' + environment)
module.exports = config

在封装axios时引入使用
http.js

import { baseUrl } from '@/config'

console.log(baseUrl)

const request = axios.create({
  baseURL: baseUrl, // 环境的切换
  timeout: 10 * 1000 // Timeout 请求超时时间
  // withCredentials: true // 允许跨域携带cookie信息
})

2. 因为是移动端项目,所以需要做适配方案,我选择的是使用rem,这里借助了两个插件

  • postcss-pxtorem 是一款 postcss 插件,用于将单位转化为 rem
  • lib-flexible 用于设置 rem 基准值
// 安装插件
cnpm install lib-flexible postcss-pxtorem --save-dev
// main.js 导入
// 移动端适配
 import ‘lib-flexible/flexible’; 

创建.postcssrc.js
下面提供了一份基本的 postcss 配置,可以在此配置的基础上根据项目需求进行修改

// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
  plugins: {
    autoprefixer: {
      overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 8']
    },
    'postcss-pxtorem': {
      rootValue: 75,
      propList: ['*']
    }
  }
}

3.Axios封装以及接口管理

axios的封装和api接口的统一管理,其实主要目的就是在帮助我们简化代码和利于后期的更新维护。
一般我会在项目的src目录中,新建一个network文件夹,作为我们的网络请求模块,然后在里面新建一个http.js和一个api.js文件和一个reques.js。http.js文件用来封装我们的axios,api.js用来统一管理我们的接口url,request.js用来封装axios请求,配置baseURL添加拦截器, http.js对外暴露我们放在的api方法。

4.VantUI 组件按需加载

babel-plugin-import 是一款 babel 插件,它会在编译过程中将
import 的写法自动转换为按需引入的方式

  • 安装插件
npm i babel-plugin-import -D
  • 在babel.config.js 设置
// 对于使用 babel7 的用户,可以在 babel.config.js 中配置
const plugins = [
  [
    'import',
    {
      libraryName: 'vant',
      libraryDirectory: 'es',
      style: true
    },
    'vant'
  ]
]
module.exports = {
  presets: [['@vue/cli-plugin-babel/preset', { useBuiltIns: 'usage', corejs: 3 }]],
  plugins
}
  • 使用组件
    项目在 src/plugins/vant.js 下统一管理组件,用哪个引入哪个,无需在页面里重复引用
// 按需全局引入 vant组件
import Vue from 'vue'
import { Button, List, Cell, Tabbar, TabbarItem } from 'vant'
Vue.use(Button)
Vue.use(Cell)
Vue.use(List)
Vue.use(Tabbar).use(TabbarItem)

(element-ui小技巧)
vue add element
这行命令可以帮助我们快速引入element-ui,可以选择全局引入和按需引入,自动配置好所需文件。但是要注意最好是在项目创建之初执行,否则可能出现BUG

5.配置Sass 全局样式

1、安装

npm install node-sass --save-dev
npm install sass-loader@7.3.1  --save-dev

2、配置
//vue.config.js
module.exports = {
	//配置全局样式变量
	css: {
		loaderOptions: {
			sass: {
				data: `@import "@/assets/style/common/variables.scss";`
			}
		}
	}
}

3、使用
在每个vue文件中的style,添加lang=“scss”

<style lang="scss" scoped>
/* 写入scss */

</style>

目录结构
vue-h5-template 所有全局样式都在 @/src/assets/css 目录下设置

├── assets
│   ├── css
│   │   ├── index.scss               # 全局通用样式
│   │   ├── mixin.scss               # 全局mixin
│   │   └── variables.scss           # 全局变量

6. Vuex状态管理

vuex 是一个专为vue.js开发的状态管理器,采用集中式存储的所有组件状态

  1. 基本使用:新建store.js文件,最后在main.js中引入,并挂载到实列上
 import Vue from 'vue'
   import Vuex from 'vuex'
   Vue.use(Vuex)
   const state = {}
   const getters = {}
   const mutations = {}
   const actions = {}
   export default new Vuex.Store({
       state,
       getters,
       mutations,
       actions
   })

做好这些配置能大大提高我们的开发效率,并且更方便后期对项目的一个维护

7.组件的开发

整个项目采用组件拆分的思想开发的,这次开发的项目有首页、分类、登录、购物车、以及个人中心等等。还有些公共组件,在移动端项目里都是比较常用的,比如有上拉加载、吸顶、顶部导航栏、搜索框、以及底部Tabbar…(按实际项目而定)

6. 优化

最后就是项目优化,优化分为代码优化,和webpack打包优化。

一、代码优化

使用keep-alive缓存不活动的组件(重点)

keep-alive是一个抽象组件:它自身不会渲染一个DOM元素,也不会出现在父组件链中;使用keep-alive包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。

  • 在动态组件中的应用
<keep-alive :include="whiteList" :exclude="blackList" :max="amount">
     <component :is="currentComponent"></component>
</keep-alive>
  • 在vue-router中的应用
<keep-alive :include="whiteList" :exclude="blackList">
    <router-view></router-view>
</keep-alive>

include定义缓存白名单,keep-alive会缓存命中的组件;exclude定义缓存黑名单,被命中的组件将不会被缓存;
很多时候也可以配合路由的meta属性使用

export default[
 {
  path:'/',
  name:'home',
  components:Home,
  meta:{
    keepAlive:true //需要被缓存的组件
 },
 {
  path:'/book',
  name:'book',
  components:Book,
  meta:{
     keepAlive:false //不需要被缓存的组件
 } 
]
<keep-alive>
  <router-view v-if="this.$route.meat.keepAlive"></router-view>
  <!--这里是会被缓存的组件-->
</keep-alive>
<router-view v-if="!this.$route.meat.keepAlive"></router-view>
<!--这里是不会被缓存的组件-->

使用路由懒加载(重点)

Vue 是单页面应用,可能会有很多的路由引入 ,这样使用 webpcak 打包后的文件很大,当进入首页时,加载的资源过多,页面会出现白屏的情况,不利于用户体验。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应的组件,这样就更加高效了。这样会大大提高首屏显示的速度,但是可能其他的页面的速度就会降下来。

//最流行的写法,es6语法
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
  mode: 'history',
  routes: [
   {
      path: '/',
      component: ()=>import('@/components/DefaultIndex') ,
      children: [
        {
          path: '',
          component: ()=>import('@/components/Index')
         },
        {
          path: '*',
          redirect: '/Index'
        }
      ]
})

图片懒加载(重点)

对于图片过多的页面,为了加速页面加载速度,所以很多时候我们需要将页面内未出现在可视区域内的图片先不做加载, 等到滚动到可视区域后再去加载。这样对于页面加载性能上会有很大的提升,也提高了用户体验。我们在项目中使用 Vue 的 vue-lazyload 插件

npm引入:npm i vue-lazyload -S
CDN引入:[https://unpkg.com/vue-lazyload/vue-lazyload.js](https://unpkg.com/vue-lazyload/vue-lazyload.js)

使用:在main.js中

import Vue from 'vue'
import App from './App.vue'
import VueLazyload from 'vue-lazyload'
 
Vue.use(VueLazyload)
 
// or with options
Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: 'dist/error.png',
  loading: 'dist/loading.gif',
  attempt: 1
})
 
new Vue({
  el: 'body',
  components: {
    App
  }
})

template:

<ul>
  <li v-for="img in list">
    <img v-lazy="img.src" >
  </li>
</ul>

使用节流防抖函数(性能优化)(重点)

那么在 vue 中怎么使用呢:
在公共方法中(如 untils.js 中),加入函数防抖和节流方法

// 防抖
export function _debounce(fn, delay) {
    var delay = delay || 200;
    var timer;
    return function () {
        var th = this;
        var args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            timer = null;
            fn.apply(th, args);
        }, delay);
    };
}
// 节流
export function _throttle(fn, interval) {
    var last;
    var timer;
    var interval = interval || 200;
    return function () {
        var th = this;
        var args = arguments;
        var now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(function () {
                last = now;
                fn.apply(th, args);
            }, interval);
        } else {
            last = now;
            fn.apply(th, args);
        }
    }
}

在需要使用的组件引用

import { _debounce } from "@/utils/public";

在 methods 中使用

 methods: {
    // 改变场数
    changefield: _debounce(function(_type, index, item) {
        // do something ...
    }, 200)
  }

函数防抖和函数节流都是防止某一时间频繁触发,但是这两兄弟之间的原理却不一样。
函数防抖是某一段时间内只执行一次,而函数节流是间隔时间执行。

应用场景
_debounce

  • search搜索框
  • window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次

_throttle

  • 鼠标不断点击触发,mousedown(单位时间内只触发一次)
  • 拖拽事件,每拖动1px都会触发onmousemove(可以用throttle优化,每秒触发一次)
  • 监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断

v-for 遍历必须为 item 添加 key,且避免同时使用 v-if
v-for 遍历必须为 item 添加 key

在列表数据进行遍历渲染时,需要为每一项 item 设置唯一 key 值,方便 Vue.js 内部机制精准找到该条列表数据。当 state
更新时,新的状态值和旧的状态值对比,较快地定位到 diff 。

v-for 遍历避免同时使用 v-if

v-for 比 v-if 优先级高,如果每一次都需要遍历整个数组,将会影响速度,尤其是当之需要渲染很小一部分的时候,必要情况下应该替换成
computed 属性。

推荐:

<template>
  <div class="home">
    <ul>
      <li
        v-for="user in activeUsers"
        :key="user.id">
        {{ user.name }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data(){
    return {
      users:[{id:1,name:'zhangsan',isActive:true},{id:2,name:'lisi',isActive:true},{id:3,name:'wangwu',isActive:false},{id:4,name:'maliu',isActive:true},]
    }
  },
  computed: {
    activeUsers: function () {
    //  [js 的filter()方法](https://www.cnblogs.com/qiu2841/p/8961017.html)
      return this.users.filter(function (user) {
          return user.isActive
      })
    }
  }
}
</script>

不推荐:

<ul>
  <li
    v-for="user in users"
    v-if="user.isActive"
    :key="user.id">
    {{ user.name }}
  </li>
</ul>

v-if 和 v-show 区分使用场景
v-if 是 真正 的条件渲染,因为它会确保在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建;也是惰性的:如果在初始渲染时条件为假,则什么也不做——直到条件第一次变为真时,才会开始渲染条件块。

v-show就简单得多, 不管初始条件是什么,元素总是会被渲染,并且只是简单地基于 CSS 的 display 属性进行切换。

所以,v-if 适用于在运行时很少改变条件,不需要频繁切换条件的场景; v-show则适用于需要非常频繁切换条件的场景。

computed 和 watch 区分使用场景
computed: 是计算属性,依赖其它属性值,并且 computed 的值有缓存,只有它依赖的属性值发生改变,下一次获取 computed 的值时才会重新计算 computed 的值

watch: 更多的是「观察」的作用,类似于某些数据的监听回调 ,每当监听的数据变化时都会执行回调进行后续操作

运用场景:

  • 当我们需要进行数值计算,并且依赖于其它数据时,应该使用 computed,因为可以利用 computed 的缓存特性,避免每次获取值时,都要重新计算
  • 当我们需要在数据变化时执行异步或开销较大的操作时,应该使用 watch,使用 watch 选项允许我们执行异步操作 ( 访问一个 API ),限制我们执行该操作的频率,并在我们得到最终结果前,设置中间状态。这些都是计算属性无法做到的

长列表性能优化
Vue 会通过 Object.defineProperty 对数据进行劫持,来实现视图响应数据的变化,然而有些时候我们的组件就是纯粹的数据展示,不会有任何改变,我们就不需要 Vue 来劫持我们的数据,在大量数据展示的情况下,这能够很明显的减少组件初始化的时间,那如何禁止 Vue 劫持我们的数据呢?可以通过 Object.freeze 方法来冻结一个对象,一旦被冻结的对象就再也不能被修改了

export default {
  data: () => ({
    users: {}
  }),
  async created() {
    const users = await axios.get("/api/users");
    this.users = Object.freeze(users);
  }
};

事件的销毁
Vue 组件销毁时,会自动清理它与其它实例的连接,解绑它的全部指令及事件监听器,但是仅限于组件本身的事件。 如果在 js 内使用 addEventListene 等方式是不会自动销毁的,我们需要在组件销毁时手动移除这些事件的监听,以免造成内存泄露,如:

created() {
  addEventListener('click', this.click, false)
},
beforeDestroy() {
  removeEventListener('click', this.click, false)
}

二、webpack打包优化

项目开始时webpack配置

vue-cli3以后,我们修改webpack配置,需要自己在项目根路径下创建vue.config.js文件。

配置 proxy 跨域

使用vue-cli发开项目,在本地开发环境中,如果遇到跨域的问题。可以通过配置proxy的方式,解决跨域问题:

module.exports = {
  devServer: {
   open: false, // 自动启动浏览器
   host: '0.0.0.0', // localhost
   port: 6060, // 端口号
   hotOnly: false, // 热更新

   overlay: {
      //  当出现编译器错误或警告时,在浏览器中显示全屏覆盖层
      warnings: false,
      errors: true
    },
    proxy: {
      //配置跨域
      '/api': {
        target: 'https://www.test.com', // 接口的域名
        // ws: true, // 是否启用websockets
        changOrigin: true, // 开启代理,在本地创建一个虚拟服务端
        pathRewrite: {
          '^/api': '/'
        }
      }
    }
  }
}

配置完成后,当我们在去请求https://www.test.com/v1/api/userinfo接口时,就可以这么写

this.axios({
url:'/api/v1/api/userinfo',
method:'get'
}).then(res=>{
//......
})

配置 alias 别名

使用vue-cli开发项目,最大特色是组件化。组件中频繁引用其他组件或插件。我们可以把一些常用的路径定义成简短的名字。方便开发中使用。

//加载path模块
const path = require('path')
//定义resolve方法,把相对路径转换成绝对路径
const resolve = dir => path.join(__dirname, dir)

module.exports = {
  chainWebpack: config => {
    // 添加别名
    config.resolve.alias
      .set('@', resolve('src'))
      .set('assets', resolve('src/assets'))
      .set('api', resolve('src/api'))
      .set('views', resolve('src/views'))
      .set('components', resolve('src/components'))
  }
}

配置完成后,我们在项目中可以这样写路径

//之前这么写
import Home from '../views/Home.vue'
//配置alias别名后
import Home from 'views/Home.vue'
//也可以这么写
import Home from '@/views/Home.vue'

项目结束后打包前webpack配置

目的:

  • 提高打包速度
  • 减小项目体积、提高首屏加载速度
  • 提高用户体验(骨架屏)

项目开发完成后,运行npm run build进行打包操作。打包前对webpack配置

module.exports = {
  publicPath: './', // 静态资源路径(默认/,打包后会白屏)
  outputDir: 'dist', // 打包后文件的目录 (默认为dist)
  assetsDir: 'static', //  outputDir的静态资源(js、css、img、fonts)目录  默认为‘’没有单独目录js/css/img在根目录中。
  }

1. 去除生产环境sourceMap

问题: vue项目打包之后js文件夹中,会自动生成一些map文件,占用相当一部分空间
sourceMap资源映射文件,存的是打包前后的代码位置,方便开发使用,这个占用相当一部分空间。
map文件的作用在于:项目打包后,代码都是经过压缩加密的,如果运行时报错,输出的错误信息无法准确得知是哪里的代码报错,有了map就可以像未加密的代码一样,准确的输出是哪一行哪一列有错。

生产环境是不需要sourceMap的,如下配置可以去除

module.exports = {
  //去除生产环境的productionSourceMap
  productionSourceMap: false,
}

2. 去除console.log打印以及注释
下载插件

cnpm install uglifyjs-webpack-plugin --save-dev
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const isProduction = process.env.NODE_ENV === 'production';

  configureWebpack: config => {
    const plugins = [];
    if (isProduction) {
      plugins.push(
        new UglifyJsPlugin({
          uglifyOptions: {
            output: {
              comments: false, // 去掉注释
            },
            warnings: false,
            compress: {
              drop_console: true,
              drop_debugger: false,
              pure_funcs: ['console.log']//移除console
            }
          }
        })
      )
    }
  },

3. 使用CDN 加速优化

cdn优化是指把第三方库比如(vue,vue-router,axios)通过cdn的方式引入项目中,这样vendor.js会显著减少,并且大大提升项目的首页加载速度,下面是具体操作:

// 是否为生产环境
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: [
        
    ],
    // 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/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的title标签下面加上以下代码:

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


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

4. 对资源文件进行压缩
下载插件:

cnpm i compression-webpack-plugin -D
const CompressionWebpackPlugin = require('compression-webpack-plugin')

module.exports = {
  // 根据你的实际情况更改这里
  publicPath,
  assetsDir: 'assets',
  lintOnSave: true,
  configureWebpack: {
    plugins:[
      new CompressionWebpackPlugin({
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        // test: /\.js$|\.html$|\.json$|\.css/,
        test: /\.js$|\.json$|\.css/,
        threshold: 10240, // 只有大小大于该值的资源会被处理
        minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
        // deleteOriginalAssets: true // 删除原文件
      })
    ],
  },
}

压缩后也会节省一部分空间,但后端要对nginx修改,配合前端
nginx配置示例:

location ~ .*\.(js|json|css)$ {
    gzip on;
    gzip_static on; # gzip_static是nginx对于静态文件的处理模块,该模块可以读取预先压缩的gz文件,这样可以减少每次请求进行gzip压缩的CPU资源消耗。
    gzip_min_length 1k;
    gzip_http_version 1.1;
    gzip_comp_level 9;
    gzip_types  text/css application/javascript application/json;
    root /dist;
}

nginx需要安装http_gzip_static_module以支持gzip_static

5. 图片压缩
下载插件:

npm install image-webpack-loader --save-dev
module.exports = {
  // 根据你的实际情况更改这里
  publicPath,
  assetsDir: 'assets',
  lintOnSave: true,
  // image 压缩
   config.module
      .rule('images')
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({
        bypassOnDebug: true
      })
      .end()}

只打包改变的文件

const { HashedModuleIdsPlugin } = require('webpack');
configureWebpack: config => {    
    const plugins = [];
    plugins.push(
        new HashedModuleIdsPlugin()
    )
}

6. 公共代码抽离,写在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'
            }
        }
    }
}

配置 打包分析

cnpm i webpack-bundle-analyzer -D

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

module.exports = {
  chainWebpack: config => {
    // 打包分析
    if (IS_PROD) {
      config.plugin('webpack-report').use(BundleAnalyzerPlugin, [
        {
          analyzerMode: 'static'
        }
      ])
    }
  }
}

7. 骨架屏

安装插件 npm install vue-skeleton-webpack-plugin

在src下新建Skeleton文件夹,其中新建index.js以及index.vue,在其中写入以下内容,其中,骨架屏的index.vue页面样式请自行编辑

index.js

import Vue from 'vue'
import home from './index.vue'
import list from './a.vue'
export default new Vue({
  components: {
    home,
    list
  },
  template: `
  <div>
   <home id="home" style="display:none"/>
   <list id="list" style="display:none"/>
  </div>
 `
})

骨架屏页面

<template>
  <div class="skeleton-wrapper">
    <header class="skeleton-header"></header>
    <section class="skeleton-block">
      <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgMTA4MCAyNjEiPjxkZWZzPjxwYXRoIGlkPSJiIiBkPSJNMCAwaDEwODB2MjYwSDB6Ii8+PGZpbHRlciBpZD0iYSIgd2lkdGg9IjIwMCUiIGhlaWdodD0iMjAwJSIgeD0iLTUwJSIgeT0iLTUwJSIgZmlsdGVyVW5pdHM9Im9iamVjdEJvdW5kaW5nQm94Ij48ZmVPZmZzZXQgZHk9Ii0xIiBpbj0iU291cmNlQWxwaGEiIHJlc3VsdD0ic2hhZG93T2Zmc2V0T3V0ZXIxIi8+PGZlQ29sb3JNYXRyaXggaW49InNoYWRvd09mZnNldE91dGVyMSIgdmFsdWVzPSIwIDAgMCAwIDAuOTMzMzMzMzMzIDAgMCAwIDAgMC45MzMzMzMzMzMgMCAwIDAgMCAwLjkzMzMzMzMzMyAwIDAgMCAxIDAiLz48L2ZpbHRlcj48L2RlZnM+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgwIDEpIj48dXNlIGZpbGw9IiMwMDAiIGZpbHRlcj0idXJsKCNhKSIgeGxpbms6aHJlZj0iI2IiLz48dXNlIGZpbGw9IiNGRkYiIHhsaW5rOmhyZWY9IiNiIi8+PHBhdGggZmlsbD0iI0Y2RjZGNiIgZD0iTTIzMCA0NGg1MzN2NDZIMjMweiIvPjxyZWN0IHdpZHRoPSIxNzIiIGhlaWdodD0iMTcyIiB4PSIzMCIgeT0iNDQiIGZpbGw9IiNGNkY2RjYiIHJ4PSI0Ii8+PHBhdGggZmlsbD0iI0Y2RjZGNiIgZD0iTTIzMCAxMThoMzY5djMwSDIzMHpNMjMwIDE4MmgzMjN2MzBIMjMwek04MTIgMTE1aDIzOHYzOUg4MTJ6TTgwOCAxODRoMjQydjMwSDgwOHpNOTE3IDQ4aDEzM3YzN0g5MTd6Ii8+PC9nPjwvc3ZnPg==">
      <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgMTA4MCAyNjEiPjxkZWZzPjxwYXRoIGlkPSJiIiBkPSJNMCAwaDEwODB2MjYwSDB6Ii8+PGZpbHRlciBpZD0iYSIgd2lkdGg9IjIwMCUiIGhlaWdodD0iMjAwJSIgeD0iLTUwJSIgeT0iLTUwJSIgZmlsdGVyVW5pdHM9Im9iamVjdEJvdW5kaW5nQm94Ij48ZmVPZmZzZXQgZHk9Ii0xIiBpbj0iU291cmNlQWxwaGEiIHJlc3VsdD0ic2hhZG93T2Zmc2V0T3V0ZXIxIi8+PGZlQ29sb3JNYXRyaXggaW49InNoYWRvd09mZnNldE91dGVyMSIgdmFsdWVzPSIwIDAgMCAwIDAuOTMzMzMzMzMzIDAgMCAwIDAgMC45MzMzMzMzMzMgMCAwIDAgMCAwLjkzMzMzMzMzMyAwIDAgMCAxIDAiLz48L2ZpbHRlcj48L2RlZnM+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgwIDEpIj48dXNlIGZpbGw9IiMwMDAiIGZpbHRlcj0idXJsKCNhKSIgeGxpbms6aHJlZj0iI2IiLz48dXNlIGZpbGw9IiNGRkYiIHhsaW5rOmhyZWY9IiNiIi8+PHBhdGggZmlsbD0iI0Y2RjZGNiIgZD0iTTIzMCA0NGg1MzN2NDZIMjMweiIvPjxyZWN0IHdpZHRoPSIxNzIiIGhlaWdodD0iMTcyIiB4PSIzMCIgeT0iNDQiIGZpbGw9IiNGNkY2RjYiIHJ4PSI0Ii8+PHBhdGggZmlsbD0iI0Y2RjZGNiIgZD0iTTIzMCAxMThoMzY5djMwSDIzMHpNMjMwIDE4MmgzMjN2MzBIMjMwek04MTIgMTE1aDIzOHYzOUg4MTJ6TTgwOCAxODRoMjQydjMwSDgwOHpNOTE3IDQ4aDEzM3YzN0g5MTd6Ii8+PC9nPjwvc3ZnPg==">
    </section>
  </div>
</template>
 
<script>
  export default {
    name: 'skeleton'
  }
</script>
 
<style scoped>
  .skeleton-header {
    height: 40px;
    background: #1976d2;
    padding:0;
    margin: 0;
    width: 100%;
  }
  .skeleton-block {
    display: flex;
    flex-direction: column;
    padding-top: 8px;
  }
 
</style>

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/Skeleton/index.js'),
        },
      },
      minimize: true,
      quiet: true,
      // 如果不设置那么所有的路由都会共享这个骨架屏组件
      router: {
        mode: 'hash',
        // 给对应的路由设置对应的骨架屏组件,skeletonId的值根据组件设置的id
        routes: [
	      { path: '/list', skeletonId: 'home' },
	      { path: '/kc', skeletonId: 'list' },
	    ]
    }))
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值