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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With