Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using webpack code splitting, how to load chunks and HTML layout?

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?

like image 880
mguijarr Avatar asked Nov 10 '15 21:11

mguijarr


People also ask

How are webpack chunks loaded?

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.

How does code splitting work webpack?

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.

Can webpack split code into separate files?

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.

How does code splitting work?

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.


1 Answers

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

like image 166
Grgur Avatar answered Oct 27 '22 15:10

Grgur