Vue代码分割懒加载

webpack > 2的时代,vue作代码分割懒加载更加的easy,不须要loader,不须要require.ensure。
import解决一切。vue

分割层级

Vue代码分割懒加载包含以下几个层级:

一、 组件层级分割懒加载
二、 router路由层级
三、 Vuex 模块webpack

组件层级代码分割

//全局组件
Vue.component('AsyncComponent', () => import('./AsyncComponent'))

//局部注册组件
new Vue({
  // ...
  components: {
    'AsyncComponent': () => import('./AsyncComponent')
  }
})

// 若是不是default导出的模块
new Vue({
  // ...
  components: {
    'AsyncComponent': () => import('./AsyncComponent').then({ AsyncComponent }) => AsyncComponent
  }
})

路由层级代码分割

const AsyncComponent= () => import('./AsyncComponent')

new VueRouter({
  routes: [
    { path: '/test', component: AsyncComponent}
  ]
})

Vuex 模块代码分割,vuex中有动态注册模块方法,同时也是加上import

const store = new Vuex.Store()

import('./store/test').then(testModule => {
  store.registerModule('test', testModule)
})

总结

在通常项目中,咱们按照router和components层面分割(或者只使用router分割)就足够了。大型项目可能三者都会用到,但用法都很简单,不是么?web

相关文章
相关标签/搜索