Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I bundle react.js apps into multiple modules?

Let's say I have a website with multiple tabs, built with react.js, and each tab contains a large amount of data. Normally webpack bundles react apps into a single bundle, but this would be a waste of resources if you never visit one of the tabs. Is it possible to break it into separate bundles without having to re-bundle react core & react DOM, and then call these extra static modules upon request?

I'm open to different suggestions - webpack, systemjs etc.

like image 589
Nodeocrat Avatar asked Apr 13 '26 13:04

Nodeocrat


1 Answers

First, check your architecture and make sure you actually need this. Considering the typical scenario in which only the "infrastructure" is part of the bundle and all data is downloaded via Ajax as they are needed, it is kind of unlikely (not impossible) that you will end up with a particularly large bundle when you properly take care of optimization.

Back to your question...

Bear in mind that this might not be a walk in the park. From my experience, when you're trying to do something a little off the dotted line, problems start to pop up down the road. You might have problems with server-rendering, redux or whatever.

Anyway, you got 2 options:

1) Using a multi-page app configuration

Webpack will output multiple "chunks" with you configure it to have multiple entry points like this:

module.exports = {
    entry: {
        p1: "./page1",
        p2: "./page2",
        p3: "./page3"
    },
    output: {
        filename: "[name].entry.chunk.js"
    }
}

You can even have "common chunks". Take a look here.

2) Using code splitting

There's a Webpack loader called bundle-loader that offers a lazy option that allows modules to be actually downloaded as they are needed. I came across this loader when I was reading the React-Router 4 documentation. They even provide an example which doesn't require the router at all, check it here.

like image 52
André Pena Avatar answered Apr 16 '26 14:04

André Pena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!