为什么需要懒加载
在单页应用中,如果没有应用懒加载,运用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分割)就足够了。大型项目可能三者都会用到,但用法都很简单,不是么?
相关推荐:
用js实现懒加载和跨域的实现步骤
javascript实现图片的懒加载方法介绍
图片的懒加载问题
以上就是关于vue代码分割懒加载的详细内容。
