bit
bit copied to clipboard
How to override base config to enable tree shaking with Material-UI
Description
When using a Material-UI component like Button in a Create React App, the default configurations allow tree shaking
when using imports like import { Button } from '@material-ui/core'; so the bundle is limited to this code.
When using a component from my Bit collection that has this same import on another project, and analyzing bundles
size, I noticed that the component included alot of dead code.
I would like to have help on the basics of how I can achieve the same on Bit, or if this could be a possible feature to add this behavior to the default webpack config in Bit.
Specifications
- Harmony workspace
- Bit version: 0.0.471 (waiting a bugfix to upgrade)
- Node version: 14.16.0
- yarn version: npm 6.14.11/ yarn 1.22.10
- Platform: Windows 10
Context and additional information
To reproduce this here are the steps:
Bit workspace
- Create a new harmony workspace and set your defaultScope.
- Run
bit install @material-ui/core(using 4.12.3 in my case) - Use
bit create react-component ui/mui-button, remove *.spec.tsx we won't need it. - In the
button.tsx, replace the divs by Material-UI<Button variant="contained">..., using import mentionned in Description above. - compile, tag and export to bit.dev
Consuming project
- I used
npx create-react-app . --template typescript - Import with npm the mui-button component we made earlier
- Use it in App
- For checking the bundles I used
source-map-explorer
Here is the result when installing the MuiButton we made from our scope on bit.dev:

If I code the same exact MuiButton, but directly in the CRA project, the base config provide the optimized result:

Thanks for any help/advices !
In your setup, which environment configuration you used for your component?
The setup is on "*": { "teambit.react/react": {} } in the "teambit.workspace/variants"
FYI @p-l-l and anyone else interested here We will be moving soon to targeting ESM by default from bit's component compilation (can be adjusted by overriding an env's tsconfig), which should remedy this issue immediately.
@benjgil @itaymendel hello,what's the progress for this ESM feature,I have the same issue
Odd, I see your bundle is using @material/core/esm, and also @material/core has sideEffects: false.
These two together should enable tree shaking.
Look into:
- https://webpack.js.org/guides/tree-shaking/
- https://webpack.js.org/configuration/optimization
You can also try this ESM env component that @giteden created, it should output correct ESM packages 🙂 https://bit.cloud/learnbit/react/envs/react-esm
use new react env that comes with ESM out of the box - https://bit.cloud/teabmit/react/react-env