-
Notifications
You must be signed in to change notification settings - Fork 0
The Gory Details
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.)
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_Intermediategets a promise viathis.props.children. It checks to see ifthis.state.childis set. It isn't, so - It calls
thenon 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.
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.