I have a React app created with CRA. The app is built for two environments: website and browser extension which replaces a speed dial. Whereas it is nice to use dynamic imports for website, it would be good to bundle some pages into main chunk, so that there is no splashscreen when opening a new tab.
Do you have any idea how to conditionally use dynamic imports basing on environment variable? I've tried the following approach:
import WebsktopEager from 'pages/app/Websktop';
const WebsktopLazy = lazy(() => import('pages/app/Websktop'));
const Websktop = process.env.REACT_APP_TARGET === 'extension' ? WebsktopEager : WebsktopLazy;
I expected that webpack's tree shaking would remove dead code basing on the condition, but WebsktopEager is still bundled into a main chunk, even though process.env.REACT_APP_TARGET !== 'extension'.
Based on your code, cherry-picked bundling won't happen just because process.env.REACT_APP_TARGET === 'extension' is present as you expected; because it'll only work on runtime!
So CRA will be optimistic while bundling the code, and will bundle eager imports as well.
What you can do is have two separate entry files, of sorts: For eg -
main.eager.js // containing your eager imports
main.lazy.js // containing your dynamic/lazy imports
Now have a custom webpack config to separately build the projects based on any condition, environment variables that you'd like to use. And the entry point for those bundles can be differentiated based on the above said files
But ofcourse custom webpack config would require you to execute npm run eject command. So take a look at articles about that online