Ash
Ash

Reputation: 896

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.

Upvotes: 3

Views: 4794

Answers (1)

Andre Pena
Andre Pena

Reputation: 59336

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.

Upvotes: 6

Related Questions