vue项目首屏打开速度慢?我来带你飞。

1,355 阅读1分钟

最近接手了一个后台管理系统,技术栈主要是vue全家桶+elementui,老大打开测试环境页面的时候,说看到首页需要6秒钟,那如何进行优化呢?

首先我们需要安装webpack-bundle-analyzer

// webpack.prod.conf.js
if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
// config/index.js
build: {
  // Run the build command with an extra argument to
  // View the bundle analyzer report after build finishes:
  // `npm run build --report`
  // Set to `true` or `false` to always turn it on or off
  bundleAnalyzerReport: process.env.npm_config_report
}

运行npm run build --report

我们可以看到,vendor中的elementui占了500k,怎么优化呢?

在webpack配置文件中增加,接下来就是见证奇迹的时刻。

externals: {
    'vue': 'Vue',
    'element-ui': 'ELEMENT',
    'axios': 'axios'
  },

再看一下我们的vendor体积

vendor一共才195k

那缺少的elementui文件去哪里找呢?答案是cdn引用。

之前项目里还有引用moment,但是这个库实在是太大了,在github上我找到一个跟momentapi完全一样的库,但是文件大小只要2kb。

其他优化方法还有ssr,这个最好用nuxtjs来做,自己配置ssr实在太麻烦了。

如果解决了你的问题,帮我点个赞吧