Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using two different entry points for two similar react apps

I am using react with gulp and browserify. I am working on a site where I want to embed react elements at two different locations (urls). The elements are different, but reuse most of the underlying components.

What is the proper way to tell react, which component to render where, in case you have more than one entry point?

I could easily create two different js files and load the relevant file on the respective page. But as far as I understand, that would also load all the libraries and components twice and put unnecessary load on the server.

I could also use different ids for the entry points and catch the "Target container is not a DOM element." errors in case the id is not found, but that feels wrong.

Thank you for your help!

like image 262
asPlankBridge Avatar asked May 27 '15 19:05

asPlankBridge


2 Answers

It sounds like you're asking about code splitting. For this, I recommend using webpack. There's code splitting documentation, and an example of multiple entry point code splitting.

The webpack config looks like this:

var path = require("path");
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
module.exports = {
    entry: {
        pageA: "./pageA",
        pageB: "./pageB"
    },
    output: {
        path: path.join(__dirname, "js"),
        filename: "[name].bundle.js",
        chunkFilename: "[id].chunk.js"
    },
    plugins: [
        new CommonsChunkPlugin("commons.js")
    ]
}

disclaimer: I haven't tried this.

like image 112
Brigand Avatar answered Sep 30 '22 18:09

Brigand


The separate URLs are separate HTTP requests and so the entire contents of the page get loaded afresh when someone visits either URL. Imagine the 'sources' tab of your chrome web inspector to just be a more efficient way of reading one long file with html, css, and javascript. React and all other libraries are included in that one long file for either of your pages.

Your solution to "create two different js files and load the relevant file on the respective page" is the correct answer and won't have any "unnecessary load on the server."

The solution to overloading the server would be to implement caching and serve modules over CDN.

like image 37
YPCrumble Avatar answered Sep 30 '22 19:09

YPCrumble