Maintain sane file sizes with webpack code splitting

In notebook:
Egghead Webpack
Created at:
2016-06-18
Updated:
2016-06-18
Tags:
Webpack libraries React JavaScript Performance
Demonstrates the app where you have a list of animals and if you click on an animal a small fact element with some text appears.

Each animal definition is a separate JS file (ES6 Module). 

Now imagine if we have thousands of these files and we want to load them on demand and not included them in the bundle file.

Right now the loaded as such:
  // **** facts-loader.js ****
import {$on} from '.helpers'
import * as facts from '.facts'

const ..

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

...
First, we remove the import from ​.facts
Instead he uses the ES6 ​System​ API to import them. It returns a Promise.
  // **** facts-loader.js ****
import {$on} from '.helpers'
// 1. ----
// ---- import * as facts from '.facts'

const ..

$on(factsList, 'click', ({target: {dataset: {fact}}}) => {
  if(!fact) {
    // 2. ----- remove this 
    // ---- factText.innerText = facts.defaultFact;
    // 3. ++++ use System API to import
    System.import('./facts/default-fact').then(setFactText)
    return
  }
  
  // 4. define setFactText
  function setFactText({fact:animalFact}) {
    factText.innerText = animalFact
  }
  
})

...
Demoes that indeed the module is loaded on demand and Webpack takes care of managing the script import. We only load the “default fact” so far, but no the animal facts.

Let’s add these. Webpack will dynamically create a bundle with every possible combination even if there are thousands of files.
It’s called by just specifying the folder name:
​System.import(‘./facts/‘ + fact).then(setFactText)
  // **** facts-loader.js ****
import {$on} from '.helpers'

const ..

$on(factsList, 'click', ({target: {dataset: {fact}}}) => {
  if(!fact) {
    System.import('./facts/default-fact').then(setFactText)
    return
  }
  
  // 1. ++++ add this.
  System.import(‘./facts/‘ + fact).then(setFactText)​
  
  function setFactText({fact:animalFact}) {
    factText.innerText = animalFact
  }
  
})

...
As he clicks in the browser on animal name, the bundle files are created and loaded dynamically.When he runs ​npm run​, you can see in the dist/ directory the a bundle[n].js has been created for each file.This can be used to lazy-load part of React or other modules.