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

I use webpack to build pieces, to load on demand (code splitting); each piece is a rendering of the React components into DOM elements (div). I need HTML to create these divs: how and when should I load the appropriate HTML? And how should I load pieces on demand?

I am using jQuery load function to insert HTML from files into divs container. In addition, I put the <script> tag to indicate which piece should be loaded, but I find it awkward and not elegant at all compared to the rest of my application code.

Is there a less fragile way to do this?

+6
source share
2 answers

It turns out that what I wanted to achieve can be done using react-router , I just did not know;)

 <Route name="app" component={require('./app.jsx')}> <Route path="/" name="home" component={require('./homepage-container.jsx')}/> <Route path="/otherpath" name="other" component={require('./other.jsx')}/> ... add as many routes as wanted </Route> 

Jsx files are loaded on demand, and there is no need for simple HTML since I use a reaction, the design is that every part is a component. In this example, just activate the link to #/otherpath to get the other component, which will be loaded as a child of the top-level component (a route called app ).

0
source

You must use require.ensure to dynamically load the route. Even better, if you set up your project to use Webpack 2 + Tree shake, 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); } } ] }; 

On this blog you can get the entire guide: Automatically split code for React Router

+2
source

All Articles