Guys, what’s this "tree shaking" thing that’s been popping up a lot in bundlers lately? I heard it’s like pruning dead branches from code, but what exactly does it do and how does it work? Does it just take the imported stuff, or is there more to it?
What is tree shaking in frontend optimization?
👁️ 8 views💬 2 replies❤️ 0 likes
2 Replies
Tree shaking is actually more about the build tools' (Webpack, Rollup, esbuild, etc.) compilation strategies. Let me break it down for you, buddy: say you define 10 functions in a JS module, but you only use 2 of them in the frontend. Normally, all these functions would end up in the bundle during the build process and get loaded during distribution. What tree shaking does isn't just sweeping away those unused 8 functions—it's actually **leveraging compile-time analysis to extract unused parts of the modules**.
I think the most important detail here is that to make this work, your modules need to be written in **ES Modules (ESM)** format. If you use CommonJS, say goodbye to tree shaking because it can't perform static analysis. Also, if you're using Lodash, for example, and you write `import { get } from 'lodash'` instead of `import _ from 'lodash'`, you'll only pull in the `get` function. The compiler understands this based on the import and removes unnecessary code.
But honestly, don't get too hyped. Thinking tree shaking works 100% of the time is a big misconception. For instance, if there are type definitions, some functions might linger as residue by mistake. It's not just functions that get cleaned up—dead variables and unnecessary junk get removed too. Tools like Rollup can perform more aggressive cleanup, but sometimes they clean too much, leading to runtime errors. I'd say trust it only as much as you need it.
Tree shaking isn't actually a clunky term—it's an optimization technique used by modern JS toolchains to reduce file size. If I explain how it works: during the build process, they perform static analysis, meaning they "look" at the code to detect which functions or variables are never called (dead code) and then only include the usable parts in the output. For example, if you're only using the `_.get()` method from the `lodash` library, tree shaking will leave only that method in the bundle, removing the other 300+ methods from the package.
In my experience, I get the best results when working with the ES6 module system (`import/export`). Tree shaking is enabled by default in Webpack and is standard in tools like Rollup or Vite. When something goes wrong in a project, I always check this first: if you're using the classic CommonJS `require()`, tree shaking won't work—you need to switch to ES6 modules. Also, don’t forget to add the `"sideEffects": false` line to your `package.json`; otherwise, even pure ES6 modules can end up with corrupted outputs.