按需加载
2024年03月28日
一、认识
当打包构建应用时,JavaScript
包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件或者每个页面使用的组件分割成不同的代码块,然后当路由被访问的时候或者页面使用组件的时候才加载对应组件,这样就会更加高效。
二、路由按需加载
2.1 Vue
router
配置
{
path: '/xxx',
name: 'xxx',
component: () => import('xxx'),
},
有时候我们想把某个路由下的所有组件都打包在同个异步块 (chunk
) 中。只需要使用命名 chunk
,一个特殊的注释语法来提供 chunk name
(需要 Webpack > 2.4
)
const UserDetails = () =>
import(/* webpackChunkName: "group-user" */ './UserDetails.vue')
const UserDashboard = () =>
import(/* webpackChunkName: "group-user" */ './UserDashboard.vue')
const UserProfileEdit = () =>
import(/* webpackChunkName: "group-user" */ './UserProfileEdit.vue')