Codegen Tree Shaking and Bundle Size: A Practical Guide
Quick answer: Tree shaking drops code that is never imported and has no side effects, but a generated API client often bundles every operation, model, and serializer in a structure the bundler cannot split. Your bundle shrinks only when the generator emits static ES modules, you use named imports, and nothing reaches the unused code at runtime. Why a generated client can weigh more than you…
Tree shaking is a method of dead-code removal during the build process, possible due to the static structure of ES modules. However, a generated API client often bundles every operation, model, and serializer, making the bundle larger than expected. This happens because generators aim for completeness and trimming is a separate step. When you only call three endpoints on a 120-endpoint spec, the unused 117 methods still remain in the source.
Tree shaking requires the package to ship ES module entry points and declare side effects. If a module has side effects like touching global state or importing CSS, it cannot be removed, even if not used. The package must use static ES module imports and exports, named imports, and have sideEffects declared accurately.
Module format and import style impact tree shaking. Static ES module imports and exports are more compatible, while CommonJS or dynamic require imports can block removal. Using named imports of specific resources and models instead of whole namespaces can help. The package's structure, such as one file per resource or model, aids in effective removal.
The runtime shape also matters. If methods hang off one client instance, the whole registry is reachable, making individual methods harder to prune. Plain exported functions imported by name are easier to remove.
To measure and shrink the output, use esbuild, rollup-plugin-visualizer, or webpack-bundle-analyzer. Avoid estimating from generated line count. Use named imports, confirm the package ships ESM and has an accurate sideEffects declaration, generate only needed resources, and use dynamic imports for rarely used endpoints. After trimming, verify the client calls still work against the real API.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.