首页 > Web开发 > 详细

[Webpack 2] Maintain sane file sizes with webpack code splitting

时间:2016-06-22 21:51:31      阅读:207      评论:0      收藏:0      [点我收藏+]

As a Single Page Application grows in size, the size of the payload can become a real problem for performance. In this lesson, learn how to leverage code splitting to easily implement lazy loading for your application to load only the code necessary for a particular feature or functionality.

 

Here we loads facts at the beginning. So this will be bundled into the bundle.js file. This is not good enought if the application becomes large.

import {$on} from ‘./helpers‘
import * as facts from ‘./facts‘

const factsList = document.getElementById(‘facts-list‘)
const factText = document.getElementById(‘fact-text‘)

$on(factsList, ‘click‘, ({target: {dataset: {fact}}}) => {
  if (!facts) {
      factText.innerText = facts.defaultFact
      return
  }
   factText.innerText = facts[fact]
})

 

So what we want to do is loading the file on demand. And wepack will help to load file on runtime.

import {$on} from ‘./helpers‘

const factsList = document.getElementById(‘facts-list‘)
const factText = document.getElementById(‘fact-text‘)

$on(factsList, ‘click‘, ({target: {dataset: {fact}}}) => {
    if (!fact) {
        return System.import(‘./facts/default-fact‘).then(setFactText)
    }
    System.import(‘./facts/‘ + fact).then(setFactText)

    function setFactText({fact: animalFact}) {
        factText.innerText = animalFact
    }
})

To do that, we need to tell Webpack to import file when it needed by using :

System.import(‘./facts/‘ + fact)

It returns a promise, then we do parse the stuff:

    System.import(‘./facts/‘ + fact).then(setFactText)

    function setFactText({fact: animalFact}) {
        factText.innerText = animalFact
    }

 

[Webpack 2] Maintain sane file sizes with webpack code splitting

原文:http://www.cnblogs.com/Answer1215/p/5608611.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!