使用vue-cli構(gòu)建項(xiàng)目后暑中,我們會在Router文件夾下面的index.js里面引入相關(guān)的路由組件,如:
import Hello from '@/components/Hello'
import Boy from '@/components/Boy'
import Girl from '@/components/Girl'
普通加載的缺點(diǎn)
webpack在打包的時(shí)候會把整個(gè)路由打包成一個(gè)js文件,如果頁面一多霉撵,會導(dǎo)致這個(gè)文件非常大镰吆,加載緩慢
1帘撰、require.ensure()實(shí)現(xiàn)按需加載
- 語法:
require.ensure(dependencies:String[],callback:function(require),errorCallback:function(error),chunkName:String)
- vue中使用:
const List = resolve =>{ require.ensure([],()=>{ resolve(require('./list')) },'list') }
2、vue異步組件技術(shù)
在router中配置万皿,使用這種方法可以實(shí)現(xiàn)按需加載摧找,一個(gè)組件生成一個(gè)js文件
- vue中使用:
{
path: '/home',
name: 'home',
component:resove => require(['@/components/home'],resolve)
}
3、使用動態(tài)的import()語法(推薦使用這種)
- vue中使用:
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
//沒有指定webpackChunkName,每個(gè)組件打包成一個(gè)js文件
const test1 = ()=>import('@/components/test1.vue')
const test2 = ()=>import('@/components/test2.vue')
//指定了相同的webpackChunkName牢硅,會合并打包成y一個(gè)js文件
const test3 = ()=>import(/* webpackChunkName:'grounpTest' */ '@/components/test3.vue')
const test4 = ()=>import(/* webpackChunkName:'grounpTest' */ '@/components/test4.vue')
const router = new VueRouter({
routes: [
{ path: '/test1', component: test1 },
{ path: '/test2', component: test2 },
{ path: '/test3', component: test3 },
{ path: '/test4', component: test4 }
]
})
- /* webpackChunkName: 'grounpTest' */使用命名chunk蹬耘,一個(gè)特殊的注釋語法來提供 chunk name (需要 Webpack > 2.4)