当 webpack 打包时,所有组件⼀起打包会使得 JavaScript 包⾮常⼤。下图展示了打包情况 为了进⾏组件加载优化,应设置路由懒加载,这时可以使⽤ import()(mdn、Vue)来进⾏模块动态加载,模块(和⼦模块)会分割到单独的 chunk 中;⽅法返回的 Promise 对象设置给 component,这种组件只有在被需要时才会被 Vue 执⾏并渲染。通过以上处理,可以优化项⽬的加载速度。 // router/index.js import Vue from ‘vue’ import VueRouter from ‘vue-router’ Vue.use(VueRouter) // 路由规则 const routes = [ { path: ‘/login’, name: ‘login’, component: () => import(‘@/views/login/index’) }, { path: ‘/‘, component: () => import(‘@/views/layout/index’), children: [ { path: ‘’, name: ‘home’, component: () => import(‘@/views/home/index’) }, { path: ‘/role’, name: ‘role’, component: () => import(/ webpackChunkName: ‘role’ /‘@/views/role/index’) }, { path: ‘/menu’, name: ‘menu’, component: () => import(/ webpackChunkName: ‘menu’ /‘@/views/menu/index’) }, { path: ‘/resource’, name: ‘resource’, component: () => import(/ webpackChunkName: ‘resource’ /‘@/views/resource/index’) }, { path: ‘/course’, name: ‘course’, component: () => import(/ webpackChunkName: ‘course’ /‘@/views/course/index’) }, { path: ‘/user’, name: ‘user’, component: () => import(/ webpackChunkName: ‘user’ /‘@/views/user/index’) }, { path: ‘/advert’, name: ‘advert’, component: () => import(/ webpackChunkName: ‘advert’ /‘@/views/advert/index’) }, { path: ‘/advert-space’, name: ‘advert-space’, component: () => import(/ webpackChunkName: ‘advert-space’ /‘@/views/advert-space/index’) } ] }, { path: ‘*’, name: ‘error-page’, component: () => import(/ webpackChunkName: ‘error-page’ /‘@/views/error-page/index’) } ] const router = new VueRouter({ routes }) export default router 打包时各个路由⻚⾯组件会存储在单独的 chunk 中,每个路由组件只有在被访问时才会加载,具体效果如下: 可以发现 chunk 的名称都是编号形式,没有实际语义。webpack 允许通过魔法注释给 chunk 定义名称, 可读性更强。