Skip to content

Instantly share code, notes, and snippets.

@lakshyaranganath
Last active Sep 30, 2017
Embed
What would you like to do?
dual-import
import assetsManifest from '../../build/client/assetsManifest.json';
lateChunk(app, head, initialState, route) {
return `
<style>${assets.main.styles}</style>
// inline the current route's css and assign an id to it
${!assets[route.name] ? '' : `<style id="${route.name}.css">${assets[route.name].styles}</style>`}
</head>
<body>
<div id="root">${app}</div>
<script>window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}</script>
<script>window.__ASSETS_MANIFEST__ = ${JSON.stringify(assetsManifest)}</script>
<script src="${assets.webpackManifest.js}"></script>
<script src="${assets.vendor.js}"></script>
<script src="${assets.main.js}"></script>
</body>
</html>`;
},
export default (chunkName) => {
if (!__BROWSER__) {
return Promise.resolve();
} else if (!(chunkName in window.__ASSETS_MANIFEST__)) {
return Promise.reject(`chunk not found: ${chunkName}`);
} else if (!window.__ASSETS_MANIFEST__[chunkName].css) {
return Promise.resolve(`chunk css does not exist: ${chunkName}`);
} else if (document.getElementById(`${chunkName}.css`)) {
return Promise.resolve(`css chunk already loaded: ${chunkName}`);
}
const head = document.getElementsByTagName('head')[0];
const link = document.createElement('link');
link.href = window.__ASSETS_MANIFEST__[chunkName].css;
link.id = `${chunkName}.css`;
link.rel = 'stylesheet';
return new Promise((resolve, reject) => {
let timeout;
link.onload = () => {
link.onload = null;
link.onerror = null;
clearTimeout(timeout);
resolve(`css chunk loaded: ${chunkName}`);
};
link.onerror = () => {
link.onload = null;
link.onerror = null;
clearTimeout(timeout);
reject(new Error(`could not load css chunk: ${chunkName}`));
};
timeout = setTimeout(link.onerror, 30000);
head.appendChild(link);
});
};
<IndexRoute
name="landing"
getComponent={(_, cb) => {
Promise.all([
import('./views/LandingPage/LandingPage' /* webpackChunkName: 'landing' */),
importCss('landing'),
]).then(([module]) => cb(null, module.default));
}}
/>
<Route
name="search"
path="/search/"
getComponent={(_, cb) => {
Promise.all([
import('./views/SearchResultsPage/SearchResultsPage' /* webpackChunkName: 'search' */),
importCss('search'),
]).then(([module]) => cb(null, module.default));
}}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment