Skip to content

Commit f109d0d

Browse files
committed
blog: enhance Better Tree Shaking section with examples for CommonJS destructuring
1 parent 2f7d2b2 commit f109d0d

1 file changed

Lines changed: 36 additions & 5 deletions

File tree

src/content/blog/2026-03-13-webpack-5-106.mdx

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,17 +95,48 @@ module.exports = {
9595

9696
## Better Tree Shaking for CommonJS Destructuring
9797

98-
Webpack can now statically analyze **destructuring assignments directly from CommonJS `require`** (and `module.require`) and treat only the destructured properties as referenced exports, instead of conservatively assuming the whole `exports` object is used. This improves dead-code elimination in optimized builds and can reduce bundle size in codebases that still consume CommonJS modules.
98+
Webpack can now statically analyze **destructuring assignments directly from CommonJS `require`** (and `module.require`) and treat only the destructured properties as "referenced exports", instead of conservatively assuming the whole `exports` object is used. This improves dead-code elimination in optimized builds and can reduce bundle size in codebases that still consume CommonJS modules.
9999

100-
**Examples**
100+
Consider a module that exports multiple functions, and a consumer that only destructures one of them:
101101

102102
```js
103-
// Only `a` is considered referenced
104-
const { a } = require("./module");
103+
// math.js
104+
exports.add = (a, b) => a + b;
105+
exports.divide = (a, b) => a / b;
106+
exports.multiply = (a, b) => a * b;
107+
exports.subtract = (a, b) => a - b;
105108
```
106109

107110
```js
108-
// Also supported
111+
// app.js
112+
const { add } = require("./math");
113+
114+
console.log(add(2, 3));
115+
```
116+
117+
In previous versions, webpack treated `require("./math")` as referencing the entire exports object. All four functions were included in the bundle even though only `add` is used:
118+
119+
```js
120+
// Bundled output (5.105 — simplified)
121+
const math = {
122+
add: (a, b) => a + b,
123+
subtract: (a, b) => a - b,
124+
multiply: (a, b) => a * b,
125+
divide: (a, b) => a / b,
126+
};
127+
```
128+
129+
Starting with 5.106, webpack recognizes the destructuring pattern and marks only `add` as referenced. The unused exports are eliminated during optimization:
130+
131+
```js
132+
// Bundled output (5.106 — simplified)
133+
const math_add = (a, b) => a + b;
134+
// subtract, multiply, divide - tree-shaken away
135+
```
136+
137+
This also works with `module.require`:
138+
139+
```js
109140
const { a, b } = module.require("./module");
110141
```
111142

0 commit comments

Comments
 (0)