Ok, so here's what I'd like to do, but I'm not sure how because I've only ever started create react app projects for single clients. But what if I had multiple clients? And what if instead of entire sites, it's just a drop in gallery that renders in the element of their choice?
-multiclientscript
-commoncomponents (react components)
-clientAlpha
-alpha.js (has logic, imports common components, renders components where client wants on their site)
-clientBeta
-beta.js (same as alpha.js, but might import different components, whatever)
Is it possible to set up a build with webpack or some other bundler to bundle all dependencies for each client into a single script file that the client can include on their page?
If so, can someone help me get pointed in the right direction, keeping in mind I've only done very vanilla CRA projects?
Thanks!
CodePudding user response:
Unless you need Webpack-specific features, using Rollup might be better for this (and it's easier to configure).
But yes, it's certainly possible. Your bundle entrypoint would have e.g. (might require e.g. adding event listeners to work in all possible loading phases, but you get the gist)
import * as ReactDOM fom 'react-dom';
import Gallery from './my-components/Gallery';
Array.from(document.querySelectorAll(".my-gallery")).forEach(galleryEl => {
const id = galleryEl.dataset.galleryId;
ReactDOM.render(galleryEl, <Gallery id={id} />);
});
and the client's HTML would have
<div class="my-gallery" data-id="123" />
<script src="gallery-bundle.js"></script>
and it Should Just Work from there.
Of course you might want to consider the overhead of having to ship React and React DOM in your bundle – Preact might be an option...