在vue單頁應用中,當項目不斷完善豐富時,即便使用webpack打包,文件依然是很是大的,影響頁面的加載。若是咱們能把不一樣路由對應的組件分割成不一樣的代碼塊,當路由被訪問時才加載對應的組件(也就是按需加載),這樣就更加高效了。——引自vue-router官方文檔前端
如何實現??vue
vue-router配置路由,使用vue的異步組件技術,能夠實現懶加載,代碼以下:// 每一個組件都會生成一個js文件webpack
import Vue from 'vue' import Router from 'vue-router' import Login from '../view/List.vue'; Vue.use(Router); export default new Router({ routes: [ { path: '/home/list', name: 'list', components: resolve => require(['../view/List.vue'], resolve) } ],
vue、webpack官方推薦web
狀況一:每一個組件都會打包生成一個js文件vue-router
const List = () => import('../view/List.vue') // 在路由配置中什麼都不須要改變,像往常同樣使用組件: export default new Router({ routes: [ { path: '/home/list', name: 'login', components: Login }, { path: '/home/user', name: 'user', components: User } ],
狀況二:全部組件合併打包在一個異步塊chunk中異步
const List = () => import(/* webpackChunkName: "home" */ './List.vue') const User = () => import(/* webpackChunkName: "home" */ './User.vue') // 在路由配置中什麼都不須要改變,像往常同樣使用組件: export default new Router({ routes: [ { path: '/home/list', name: 'list', components: List }, { path: '/home/user', name: 'user', components: User } ], // 在webpack.base.config.js中配置 ChunkFileName: output: { path: config.build.assetsRoot, filename: '[name].js', chunkFilename: '[name].js', publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath },
另外一種寫法,更簡潔:一樣須要在webpack.base.config.js中配置 ChunkFileName:ui
{ path: '/home/list', name: 'list', component: () => import(/* webpackChunkName:"list"*/ '../view/List.vue') }, { path: '/home/user', name: 'user', component: () => import(/* webpackChunkName:"user"*/ '../view/User.vue') },
語法以下:摘自官網code
require.ensure(dependencies: String[], callback: function(require), chunkName: String
多個路由指定相同的chunkName,在這裏chunkName爲home,會合並打包成一個js文件。component
{ path: '/home/list', name: 'list', // component:list component: r => require.ensure([], () => r(require('../view/Lst.vue')), 'home') }, { path: '/home/user', name: 'user', // component:user component: r => require.ensure([], () => r(require('../view/User.vue')), 'home') } // 在webpack.base.config.js中配置 ChunkFileName 和 publicPath: output: { path: config.build.assetsRoot, filename: '[name].js', chunkFilename: '[name].js', publicPath: './', publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath },
在實踐過程當中應該會遇到各類問題,到時候再繼續補充,前端新手,多多指教!router