vue-router配置路由,使用vue的異步組件技術,能夠實現按需加載。這種方式下一個組件生成一個js文件html
用例:vue
{ path: '/promisedemo', name: 'PromiseDemo', component: resolve => require(['../components/PromiseDemo'], resolve) }
webpack官方文檔:webpack中使用import()webpack
vue官方文檔:路由懶加載(使用import())web
用例:vue-router
// 下面2行代碼,沒有指定webpackChunkName,每一個組件打包成一個js文件。 const ImportFuncDemo1 = () => import('../components/ImportFuncDemo1') const ImportFuncDemo2 = () => import('../components/ImportFuncDemo2') // 下面2行代碼,指定了相同的webpackChunkName,會合並打包成一個js文件。 // const ImportFuncDemo = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '../components/ImportFuncDemo') // const ImportFuncDemo2 = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '../components/ImportFuncDemo2') export default new Router({ routes: [ { path: '/importfuncdemo1', name: 'ImportFuncDemo1', component: ImportFuncDemo1 }, { path: '/importfuncdemo2', name: 'ImportFuncDemo2', component: ImportFuncDemo2 } ] })
vue-router
配置路由,使用webpack的require.ensure技術,也能夠實現按需加載。segmentfault
這種狀況下,多個路由指定相同的chunkName,會合並打包成一個js文件。api
舉例以下:promise
{ path: '/promisedemo', name: 'PromiseDemo', component: resolve => require.ensure([], () => resolve(require('../components/PromiseDemo')), 'demo') }, { path: '/hello', name: 'Hello', // component: Hello component: resolve => require.ensure([], () => resolve(require('../components/Hello')), 'demo') }