Static vs Dynamic Imports
You'll learn why build tools can eliminate unused code with static ES module imports but cannot do so with dynamic require() or import() calls.
The Static vs Dynamic Divide
Tree shaking works by analyzing your code before it runs, identifying which exports you actually use and discarding the rest. This analysis requires the bundler to know exactly what you're importing at build time.
Static imports are declarations like import { foo } from './module.js'. The module path is a string literal—fixed, unchanging, predictable. The bundler can read this, trace the dependency, and determine that you only need foo, not the other exports from that module.
Dynamic imports use runtime expressions. Traditional require() calls can use variables: require(userChoice). Even ES module dynamic imports (import()) load modules conditionally or lazily. The bundler encounters these and thinks: "I don't know which module this will load until the code actually runs."
Why This Matters for Tree Shaking
Imagine a librarian organizing books before opening (build time). With static imports, you hand them a list: "I need these three specific books." They can confidently leave the rest in storage.
With dynamic imports, you say: "I might need any book depending on what happens later." The librarian must keep all books available because they can't predict your choice.
Bundlers face the same problem. A dynamic path like require('./modules/' + fileName) could reference any file in that directory. The bundler must include everything that might be imported, defeating tree shaking entirely.
Key Takeaway: Tree shaking requires static ES module imports (import ... from '...') because bundlers must analyze dependencies at build time. Dynamic imports (require() with variables, import()) prevent this analysis, forcing bundlers to include all potentially-reachable code.