vue-cli3路由懒加载不生效 - 路由懒加载 - 路由配置

5,328 阅读1分钟

按照推荐将vue的路由配置如下来实现懒加载,但是路由懒加载不生效,还是会把所有的chunk加载出来:

{   //首页
    path: '/index',
    name: 'index',
    component: () => import('@/views/index/index.vue'),
},
{   //列表
    path: '/list',
    name: 'list',
    component: () => import('@/views/list/index.vue'),
}

但在控制台却发现进入首页后会把全部的页面的js文件都加载一遍,如下图:

原来vue-cli3 默认会把所有通过import()按需加载的javascript文件加上 prefetch 。

prefetch是什么?在打包后的文件中,查看index.html我们会发现类似这个<link href=/js/chunk-118075e7.5725ab1a.js rel=prefetch><link rel="prefetch">会在页面加载完成后,利用空闲时间提前加载获取用户未来可能会访问的内容。

prefetch链接会消耗宽带,如果是在移动端,而且存在大量的chunk,那么可以关掉 prefetch 链接,手动选择要提前获取的代码区块。

//手动选定要提前获取的代码
import(webpackPrefetch: true, './someAsyncComponent.vue')

关闭prefetch:

// 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
    })
  }
}