Treeshaking failing to remove an export that's only dynamically imported
See original GitHub issueBug report
What is the current behavior?
I found a bug with treeshaking, and will link to this repo to explain it.
The RxFunctionList
file defines 2 named exported variables - one small (a graphQL fragment) and one heavy (the entire list of rxjs exports).
Another file, App
, statically imports the light export from RxFunctionList
, and dynamically imports the heavy export.
Goal: for webpack’s treeshaking to remove the heavy export from the main bundle, as we only statically import the light variable from RxFunctionList
. We want the main bundle to be free of any of the rxjs exports.
Test case | Static import only | Dynamic import only | BUG: Static AND dynamic import |
---|---|---|---|
Result | treeshaking removes rxjs exports as expected | the bundle does not contain rxjs exports (they are code split) | BUG: treeshaking fails, bundle includes rxjs exports |
Main bundle size (before minification) | 589kb | 588kb | 802kb |
Webpack bundle analzyer | |||
Branch code | static import | dynamic import | static import and dynamic import |
Steps to reproduce
- make sure your node version is 17+
git clone
this repocd frontend
yarn install
yarn build
webpack-bundle-analyzer
should open, and the main bundle should be 800+ kb (before minification).- for further proof the bundle contains rxjs, open
dist/main.bundle.js
and see that it includes rx functions likebindnodecallback
,dematerialize
Additional information
I found this discussion of a similar topic and made sure to enable Terser in my webpack config. As explained in the grid above, I am getting treeshaking to work properly when only statically importing from a file - but it fails to treeshake exports that are dynamically imported, despite the fact they are never statically imported.
Other relevant information: webpack version: 5.65 Node.js version: 17 Operating System: Mac OS Additional tools: yarn, react, typescript
Are you willing to work on this yourself
Potentially
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (5 by maintainers)
Top GitHub Comments
You can setup
splitChunks
to do it, by default we decide to keep this in one chunkYep