Skip to content

前言

众所周知vue带打包时会将文件单独打包到dist文件夹下,这会导致页面第一次加载的时候速度慢的离谱,主要原因就是页面的资源还在请求和下载,

分析

shell
npm run build --report
** ******
shell
npm intall webpack-bundle-analyzer –save-dev
** ******** **
javascript
chainWebpack: config => {
  /* 添加分析工具*/
  if (process.env.NODE_ENV === "production") {
    if (process.env.npm_config_report) {
      config
        .plugin("webpack-bundle-analyzer")
        .use(require("webpack-bundle-analyzer").BundleAnalyzerPlugin)
        .end();
      config.plugins.delete("prefetch");
    }
  }
};
shell
npm run build --report

****

路由懒加载

javascript
import ShowBlogs from '@/components/ShowBlogs'

routes:[ path: 'Blogs', name: 'ShowBlogs', component: ShowBlogs ]
javascript
routes:[ path: 'Blogs',name: 'ShowBlogs',component: () => import('./components/ShowBlogs.vue')

********

参考官网的做法:

javascript
// vue.config.js
module.exports = {
  chainWebpack: config => {
    // 移除 prefetch 插件
    config.plugins.delete('prefetch')

    // 或者
    // 修改它的选项:
    config.plugin('prefetch').tap(options => {
      options[0].fileBlacklist = options[0].fileBlacklist || []
      options[0].fileBlacklist.push(/myasyncRoute(.)+?\.js$/)
      return options
    })
  }
}
****
javascript
import(/* webpackPrefetch: true */ './someAsyncComponent.vue')

UI库按需加载


****
javascript
import ElementUI from 'element-ui'
Vue.use(ElementUI)
javascript
import { Button, Input, Pagination, Table, TableColumn, MessageBox } from 'element-ui';
Vue.use(Button)
Vue.use(Input)
Vue.use(Pagination)
Vue.prototype.$alert = MessageBox.alert
********
javascript
plugins: [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]

javascript
import { Table, TableColumn } from "element-ui";

components: {
    "el-table": Table,
    "el-table-column": TableColumn }

****
javascript
minChunks: 3

************

gzip

****
shell
npm i compression-webpack-plugin -D
****** **
javascript
const CompressionPlugin = require('compression-webpack-plugin')

configureWebpack: config => {
  if (process.env.NODE_ENV === "production") {
    // 为生产环境修改配置...
    config.mode = "production";
    return {
      plugins: [
        new CompressionPlugin({
          test: /\.js$|\.html$|\.css/, //匹配文件名
          threshold: 10240, //对超过10k的数据进行压缩
          deleteOriginalAssets: false //是否删除原文件
        })
      ]
    };
  }
};

**gzip**** ******** **
javascript
const compression = require('compression')
app.use(compression())

最终效果

后记:css是否要拆分

********
javascript
 css: {
    // 是否使用css分离插件 ExtractTextPlugin
    extract: false,
    // 开启 CSS source maps?
    sourceMap: false,
    // css预设器配置项
    loaderOptions: {},
    // 启用 CSS modules for all css / pre-processor files.
    modules: false
},

总结