Skip to content
This repository was archived by the owner on Sep 4, 2019. It is now read-only.

The Gory Details

mprast edited this page Feb 8, 2017 · 2 revisions

Step 1: The Babel Transform

The babel plugin takes a element

<SplitBrain imports={{'One': '../components/one.js'}}>
    {some expression, JSX or otherwise}
</SplitBrain>

and turns it into a call to require.ensure(). It also require()s every module before returning the child expression.

require.ensure(['../components/one.js'], function(){
    var One = require('../components/one.js');
    return {some expression, JSX or otherwise}
})

It then wraps that in an expression container, and wraps that in a SplitBrain.Chunk_Intermediate element.

<SplitBrain.Chunk_Intermediate>
   {
    require.ensure(['../components/one.js'], function(){
        var One = require('../components/one.js');
        return {some expression, JSX or otherwise}
    })
   }
</SplitBrain.Chunk_Intermediate>

So what ends up getting passed as a child to Chunk_Intermediate is a promise generated by require.ensure.

(If you're a JSX nerd you might have noticed that SplitBrain supports expression containers, even though those aren't valid top-level JSX elements, and as such can't really be the return value of require.ensure. To get around this, we strip the expression container and just return the expression that it was wrapping.)

Step 2: Render time

Chunk_Intermediate has a piece of state called child which will get asynchronously set to the component's top-level child. Calling render() on Chunk_Intermediate sets off a series of steps:

  • Chunk_Intermediate gets a promise via this.props.children. It checks to see if this.state.child is set. It isn't, so
  • It calls then on the promise with a callback that:
  • takes whatever expression the promise returns and puts it in this.state.child, at which point
  • the component re-renders and just returns this.state.child.

That's it! Eaaaaaasy peasy.

Turning it off

Disabling code splitting is pretty straightforward. In the build step we remove the require.ensure and call the inner function; i.e. instead of this:

require.ensure(['../components/one.js'], function(){
    var One = require('../components/one.js');
    return {some expression, JSX or otherwise}
})

We output this

function(){
    var One = require('../components/one.js');
    return {some expression, JSX or otherwise}
}()

The outer wrapping is the same, but the element is now SplitBrain.Passthrough instead of SplitBrain.Chunk_Intermediate:

<SplitBrain.Passthrough>
{
    function(){
        var One = require('../components/one.js');
        return {some expression, JSX or otherwise}
    }()
}
</SplitBrain.Passthrough>

SplitBrain.Passthrough just returns its children.

Clone this wiki locally