I use webpack to build chunks, to be loaded on demand (code splitting); each chunk is rendering React components into DOM elements (divs). I need HTML to create those divs: how and when should I load the corresponding HTML ? And how should I load the chunks on demand ?
I use jQuery's load
function to insert HTML from files in container divs
. In addition I put a <script>
tag to tell which chunk should be loaded but I find it clumsy and not elegant at all compared to the rest of my application code.
Is there a less brittle way to do this?
Webpack injects some code into main. js which takes care of lazy loading async chunks and stops from loading same chunks again and again. When a route changes, React router calls a Webpack function to load a chunk file and Webpack after done loading runs it, which chunk then would internally ask React to do something.
In React, code splitting involves applying the dynamic import() syntax to your components so that webpack automatically split the imported component as a separate bundle.
Code splitting is one of the most compelling features of webpack. This feature allows you to split your code into various bundles which can then be loaded on demand or in parallel.
Code splitting is the splitting of code into various bundles or components which can then be loaded on demand or in parallel. As an application grows in complexity or is maintained, CSS and JavaScripts files or bundles grow in byte size, especially as the number and size of included third-party libraries increases.
You should use require.ensure
for dynamic route loading. Even better, if you set up your project to use Webpack 2 + Tree shaking, you can use System.import
.
Here's how:
import App from 'containers/App';
function errorLoading(err) {
console.error('Dynamic page loading failed', err);
}
function loadRoute(cb) {
return (module) => cb(null, module.default);
}
export default {
component: App,
childRoutes: [
{
path: '/',
getComponent(location, cb) {
System.import('pages/Home')
.then(loadRoute(cb))
.catch(errorLoading);
}
},
{
path: 'blog',
getComponent(location, cb) {
System.import('pages/Blog')
.then(loadRoute(cb))
.catch(errorLoading);
}
}
]
};
You can get the entire guide in this blog post: Automatic Code Splitting for React Router
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With