【问题标题】:Vue3 router lazy loading does not work as expectedVue3 路由器延迟加载无法按预期工作
【发布时间】:2023-12-06 10:06:01
【问题描述】:

我有一个通过 vue-cli 创建的简单 Vue Hello-world 应用程序。有默认应该是惰性的路由器。但正如我在浏览器网络选项卡中看到的那样,它并不懒惰。它在第一页加载时立即加载所有组件。我唯一做的就是向路由器添加一条路由。它看起来像 documentation 示例。此外,正如文档所说,我已经安装了 @babel/plugin-syntax-dynamic-import 并更新了 babel.config.js。谁能告诉我这是什么问题?

这是路由器代码:

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/contact',
    name: 'Contact',
    component: () => import(/* webpackChunkName: "contact" */ '../views/Contact.vue'),
    props: {
      title: 'Contact',
      test: 'Some test value',
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

这里是 babel.config.js 文件

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ],
  plugins: [
    "@babel/plugin-syntax-dynamic-import"
  ]
}

【问题讨论】:

  • 这能回答你的问题吗? My lazy loading router painfully loads everything
  • 还有this
  • 不知道。查看 Chrome 中的性能选项卡时,我发现情况更糟。 Vue 会生成一个名为 chunk-vendors.js 的文件,大小约为 2.9MB。那是什么?
  • 那么它是块的预取吗?
  • chunk-vendors.js 是用于包含 node_modules 依赖项的块的标准名称。 Vue 本身、路由器、您正在使用的任何其他库(Vuetify、Quasar 等)这个块永远不会被延迟加载。

标签: vue.js vue-router vuejs3 vue-cli


【解决方案1】:

好的,原因是内容的预取。它以低优先级加载。这意味着它可以下载给定的资源,即使在页面中没有检测到它。资源以低优先级下载。

这是它在生成的 html 中的样子:

<!DOCTYPE html><html lang=""><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="icon" href="/favicon.ico">
    <title>vue-hello-world</title>
    <link href="/js/about.b54d7802.js" rel="prefetch">
    <link href="/js/contact.35a4dd8d.js" rel="prefetch">
    <link href="/css/app.f824e728.css" rel="preload" as="style">
    <link href="/js/app.b9f6d9e9.js" rel="preload" as="script">
    <link href="/js/chunk-vendors.2fe81e6e.js" rel="preload" as="script">
    <link href="/css/app.f824e728.css" rel="stylesheet">
</head>
<body>
    <noscript>
    <strong>We're sorry but vue-hello-world doesn't work properly without JavaScript enabled. 
        Please enable it to continue.</strong></noscript><div id="app"></div>
        <script src="/js/chunk-vendors.2fe81e6e.js"></script>
        <script src="/js/app.b9f6d9e9.js"></script>
    </body>
</html>

【讨论】:

    最近更新 更多