Skip to content

Commit

Permalink
Do not partially tree-shake unused declarations in for loops (#3943)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukastaegert authored Jan 31, 2021
1 parent 363e15d commit bc2bf95
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/ast/nodes/ForStatement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export default class ForStatement extends StatementBase {

include(context: InclusionContext, includeChildrenRecursively: IncludeChildren) {
this.included = true;
if (this.init) this.init.include(context, includeChildrenRecursively);
if (this.init) this.init.includeAllDeclaredVariables(context, includeChildrenRecursively);
if (this.test) this.test.include(context, includeChildrenRecursively);
const { brokenFlow } = context;
if (this.update) this.update.include(context, includeChildrenRecursively);
Expand Down
1 change: 1 addition & 0 deletions src/ast/nodes/VariableDeclaration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export default class VariableDeclaration extends NodeBase {

render(code: MagicString, options: RenderOptions, nodeRenderOptions: NodeRenderOptions = BLANK) {
if (
nodeRenderOptions.isNoStatement ||
areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)
) {
for (const declarator of this.declarations) {
Expand Down
3 changes: 3 additions & 0 deletions src/ast/nodes/VariableDeclarator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ export default class VariableDeclarator extends NodeBase {
): void {
this.included = true;
this.id.include(context, includeChildrenRecursively);
if (this.init) {
this.init.include(context, includeChildrenRecursively);
}
}

render(code: MagicString, options: RenderOptions) {
Expand Down
3 changes: 3 additions & 0 deletions test/function/samples/unused-for-loop-declaration/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
description: 'does not partially tree-shake unused declarations with side-effects in for loops'
};
9 changes: 9 additions & 0 deletions test/function/samples/unused-for-loop-declaration/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
let result;
let reassigned;

for (var a = (reassigned = 'reassigned'), b = 0; b < 2; b++) {
result = b;
}

assert.strictEqual(result, 1);
assert.strictEqual(reassigned, 'reassigned');

0 comments on commit bc2bf95

Please sign in to comment.