I am splitting my react code with multiple entry points in webpack, these bundles are then loaded independently at completely different pages(HTML documents).
I have a lot of shared code, and most of my shared logic is under if-else check, so this shared logic is present in all the bundles, causing the increase in bundle size.
The condition for this if-else check is based on a variable which we generate at run time, but these variables can be set based on the entrypoint.
Is it possible to set some environment variable based on entrypoints(which I can use for the if-else check), so webpack can treeshake and remove the code which is not required in the bundle?
I had a more less similar issue on my project. We needed to have different builds for different products and of course wanted to omit irrelevant code in the bundle. Might be you find something useful here
Step 1 - Create new build definitions with variables
Note - I am using
SET SOME_VARIABLE=XXXXto provide environment variable for the buildStep 2 Split your shared file into several files:
/shared/first.tsx
/shared/second.tsx
Step 3 - update your imports and point them to the specific files
// first.tsx
// second.tsx
Final Step - Use If-Else, Environmental variable and React.lazy to load your entry point
Now, if you run
npm run build:firstand check the bundle you will see that: