Tree shaking and module side effects
Quick answer
Tree shaking is a build optimization that removes code when static analysis can establish that it is not needed. ES module imports and exports provide useful static structure.
Tooling examples
Example 1. Context: projects/build-lab. Run in a fresh prepared fixture copy; see its README. Save as example.mjs in that folder; run node example.mjs. Local check available; consult validation evidence for what was asserted.
import { used } from "./effects.mjs";console.log(used());Expected observation: module initialized 7
Example 2. Context: projects/build-lab. Run in a fresh prepared fixture copy; see its README. Save as example.mjs in that folder; run node example.mjs. Local check available; consult validation evidence for what was asserted.
import "./effects.mjs";console.log("ready");Expected observation: module initialized ready
How the tooling works
An unused exported function may be removable; a top-level operation such as registering a listener or importing a stylesheet may still matter even if no exported binding is read. Tools use analysis and sometimes package metadata such as sideEffects; an incorrect assertion of purity can break the application. Dead-code elimination is not an ECMAScript requirement. Compare production artifacts and behavior after optimization, rather than assuming unused source text is always absent.
Common mistakes
Do not label every module side-effect-free when some initialize essential application behavior.
Practice
Add an unused export and a top-level log in the native lab. Compare native execution with an approved production bundler and inspect whether each operation remains.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tree shaking and module side effects — Knowledge Check
Assess tooling contracts, diagnostic reasoning and transfer to a project.
Which module operation may remain necessary even when no exported value is used?
What is the main purpose of tree shaking?
How should you verify a tree-shaking change?
In Tree shaking and module side effects, what is the expected observation for example 1 in its documented setup? import { used } from "./effects.mjs"; console.log(used());
In Tree shaking and module side effects, what is the expected observation for example 2 in its documented setup? import "./effects.mjs"; console.log("ready");