reactjs - Webpack (Craco) code splitting on build (environment-based splitting) - Stack Overflow

admin2025-04-18  2

We have a React Craco app which we serve to different markets/countries. This means the majority of the code is used by all markets, but also every market has its own code (components, functions, etc.). At the moment we do "code market splitting" in runtime checking BUILD_MODE env var, which represents a market; we have 4 markets (so we also have 4 different build script commands depending on the mentioned env var). For example:

if (BUILD_MODE === 'market1') {
  return <SomeComponentOnMarket1 />
}

And then lazy load the SomeComponentOnMarket1 component.

Going towards refactoring this, we came up with something like the following. We added components/market1, components/market2, components/market3 and components/market3 folders. Each of the folder has its own representation of a component which is used on all markets. In craco.config.js we ammended components alias and now we have the following:

'@/components': [
    path.resolve(__dirname, './src/components'),
    path.resolve(__dirname, `./src/components/markets/${process.env.REACT_APP_BUILD_MODE}`),
],

Notice the second resolve. And then in tsconfig.json we have this:

"@/components/*": [
    "./components/*",
    "./components/markets/market1/*",
    "./components/markets/market2/*",
    "./components/markets/market3/*",
    "./components/markets/market4/*"
],

Usage in the code:

import { MutualComponent } from '@/components/MutualComponent';

return (
  ...
  <MutualComponent />
)

This works as expected on build time when each market has a representation of the same named component. But it fails if that's not the case - say we only have a specific component for market3, so market3/MarketThreeSpecificComponent.tsx. This will work when building the app with BUILD_MODE set to market3, but for all other markets wil fail, since there are no market1/MarketThreeSpecificComponent.tsx or market2/MarketThreeSpecificComponent.tsx or market4/MarketThreeSpecificComponent.tsx.

Has anyone dealt with stuff like this, environment-based code splitting with webpack (Craco)? We are open to other suggestions of implementation also.

Thanks

转载请注明原文地址:http://anycun.com/QandA/1744913983a89406.html