Vue代码分割懒加载的实现方法

什么是懒加载

懒加载也叫延迟加载,即在需要的时候进行加载,随用随载。

为什么需要懒加载

在单页应用中,如果没有应用懒加载,运用webpack打包后的文件将会异常的大,造成进入首页时,需要加载的内容过多,延时过长,不利于用户体验,而运用懒加载则可以将页面进行划分,需要的时候加载页面,可以有效的分担首页所承担的加载压力,减少首页加载用时

如何与webpack配合实现组件懒加载

1、在webpack配置文件中的output路径配置chunkFilename属性

output: {
    path: resolve(__dirname, 'dist'),
    filename: options.dev ? '[name].js' : '[name].js?[chunkhash]',
    chunkFilename: 'chunk[id].js?[chunkhash]',
    publicPath: options.dev ? '/assets/' : publicPath
},

chunkFilename路径将会作为组件懒加载的路径

2、配合webpack支持的异步加载方法

  • resolve => require([URL], resolve), 支持性好
  • () => system.import(URL) , webpack2官网上已经声明将逐渐废除, 不推荐使用
  • () => import(URL), webpack2官网推荐使用, 属于es7范畴, 需要配合babel的syntax-dynamic-import插件使用, 具体使用方法如下
npm install --save-dev babel-core babel-loader babel-plugin-syntax-dynamic-import babel-preset-es2015

  

use: [{
    loader: 'babel-loader',
    options: {
    presets: [['es2015', {modules: false}]],
    plugins: ['syntax-dynamic-import']
    }
}]

引言

而在webpack > 2的时代,vue做代码分割懒加载更加的easy,不需要loader,不需要require.ensure。

import解决一切。

分割层级

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

      1、 组件层级分割懒加载

      2、 router路由层级

      3、 Vuex 模块

组件层级代码分割

//全局组件
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分割)就足够了。大型项目可能三者都会用到,但用法都很简单

猜你喜欢

转载自www.cnblogs.com/Tohold/p/9115217.html