什么是懶加載
懶加載也叫延遲加載,即在需要的時(shí)候進(jìn)行加載,隨用隨載。
為什么需要懶加載
在單頁應(yīng)用中,如果沒有應(yīng)用懶加載,運(yùn)用webpack打包后的文件將會異常的大,造成進(jìn)入首頁時(shí),需要加載的內(nèi)容過多,延時(shí)過長,不利于用戶體驗(yàn),而運(yùn)用懶加載則可以將頁面進(jìn)行劃分,需要的時(shí)候加載頁面,可以有效的分擔(dān)首頁所承擔(dān)的加載壓力,減少首頁加載用時(shí)
如何與webpack配合實(shí)現(xiàn)組件懶加載
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支持的異步加載方法
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的時(shí)代,vue做代碼分割懶加載更加的easy,不需要loader,不需要require.ensure。
import解決一切。
分割層級
Vue代碼分割懶加載包含如下幾個(gè)層級:
1、 組件層級分割懶加載
2、 router路由層級
3、 Vuex 模塊
組件層級代碼分割
//全局組件 Vue.component('AsyncComponent', () => import('./AsyncComponent')) //局部注冊組件 new Vue({ // ... components: { 'AsyncComponent': () => import('./AsyncComponent') } }) // 如果不是default導(dǎo)出的模塊 new Vue({ // ... components: { 'AsyncComponent': () => import('./AsyncComponent').then({ AsyncComponent }) => AsyncComponent } })
路由層級代碼分割
const AsyncComponent= () => import('./AsyncComponent') new VueRouter({ routes: [ { path: '/test', component: AsyncComponent} ] })
Vuex 模塊代碼分割,vuex中有動態(tài)注冊模塊方法,同時(shí)也是加上import
const store = new Vuex.Store() import('./store/test').then(testModule => { store.registerModule('test', testModule) })
總結(jié)
在一般項(xiàng)目中,我們按照router和components層面分割(或者只使用router分割)就足夠了。大型項(xiàng)目可能三者都會用到,但用法都很簡單,不是么?
好了,
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com