Skip to content

Commit bc2bf95

Browse files
authored
Do not partially tree-shake unused declarations in for loops (#3943)
1 parent 363e15d commit bc2bf95

5 files changed

Lines changed: 17 additions & 1 deletion

File tree

src/ast/nodes/ForStatement.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ export default class ForStatement extends StatementBase {
4040

4141
include(context: InclusionContext, includeChildrenRecursively: IncludeChildren) {
4242
this.included = true;
43-
if (this.init) this.init.include(context, includeChildrenRecursively);
43+
if (this.init) this.init.includeAllDeclaredVariables(context, includeChildrenRecursively);
4444
if (this.test) this.test.include(context, includeChildrenRecursively);
4545
const { brokenFlow } = context;
4646
if (this.update) this.update.include(context, includeChildrenRecursively);

src/ast/nodes/VariableDeclaration.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ export default class VariableDeclaration extends NodeBase {
8787

8888
render(code: MagicString, options: RenderOptions, nodeRenderOptions: NodeRenderOptions = BLANK) {
8989
if (
90+
nodeRenderOptions.isNoStatement ||
9091
areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)
9192
) {
9293
for (const declarator of this.declarations) {

src/ast/nodes/VariableDeclarator.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ export default class VariableDeclarator extends NodeBase {
4545
): void {
4646
this.included = true;
4747
this.id.include(context, includeChildrenRecursively);
48+
if (this.init) {
49+
this.init.include(context, includeChildrenRecursively);
50+
}
4851
}
4952

5053
render(code: MagicString, options: RenderOptions) {
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module.exports = {
2+
description: 'does not partially tree-shake unused declarations with side-effects in for loops'
3+
};
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
let result;
2+
let reassigned;
3+
4+
for (var a = (reassigned = 'reassigned'), b = 0; b < 2; b++) {
5+
result = b;
6+
}
7+
8+
assert.strictEqual(result, 1);
9+
assert.strictEqual(reassigned, 'reassigned');

0 commit comments

Comments
 (0)