vue路由按需加载
按需加载就是只有我们访问这个路由时才会加载这个js
为什么要按需加载
按照普通的加载方式:
router.js
...
import Login from '@/views/login'
import Welcome from '@/views/welcome'
export default new Router({
routes: [
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/welcome',
name: 'welcome',
component: Welcome
}
]
})
当我们执行yarn build后的文件:
webpack在打包的时候会把整个路由打包成一个js文件
如果页面一多,会导致这个文件非常大,加载缓慢
2种按需打包的方式
-
{ path: '/login', name: 'login', component: resolve => require(['@/views/login'], resolve) }
-
{ path: '/welcome', name: 'welcome', component: () => import(/* webpackChunkName: "welcome" */ '@/views/welcome') }, { path: '*', name: '404', component: () => import(/* webpackChunkName: "404" */ '@/views/404') }, { path: '/login', name: 'login', component: () => import(/* webpackChunkName: "login" */ '@/views/login') }
/* webpackChunkName: ‘grounpTest’ */使用命名chunk,一个特殊的注释语法来提供 chunk name (需要 Webpack > 2.4)没有指定webpackChunkName,每个组件各自打包成一个js文件:
{ path: '/welcome', name: 'welcome', component: () => import('@/views/welcome') }, { path: '*', name: '404', component: () => import('@/views/404') }, { path: '/login', name: 'login', component: () => import('@/views/login') }
指定了相同的webpackChunkName,会合并打包成一个js文件:{ path: '/welcome', name: 'welcome', component: () => import(/* webpackChunkName: "welcome" */ '@/views/welcome') }, { path: '*', name: '404', component: () => import(/* webpackChunkName: "welcome" */ '@/views/404') }, { path: '/login', name: 'login', component: () => import(/* webpackChunkName: "welcome" */ '@/views/login') }