diff --git a/src/ast/nodes/ForStatement.ts b/src/ast/nodes/ForStatement.ts index 1e25463d10b..15385dd214b 100644 --- a/src/ast/nodes/ForStatement.ts +++ b/src/ast/nodes/ForStatement.ts @@ -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); diff --git a/src/ast/nodes/VariableDeclaration.ts b/src/ast/nodes/VariableDeclaration.ts index 1e6f7a9a6b6..6da9123206f 100644 --- a/src/ast/nodes/VariableDeclaration.ts +++ b/src/ast/nodes/VariableDeclaration.ts @@ -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) { diff --git a/src/ast/nodes/VariableDeclarator.ts b/src/ast/nodes/VariableDeclarator.ts index 3a44d176183..fb1bb6efc20 100644 --- a/src/ast/nodes/VariableDeclarator.ts +++ b/src/ast/nodes/VariableDeclarator.ts @@ -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) { diff --git a/test/function/samples/unused-for-loop-declaration/_config.js b/test/function/samples/unused-for-loop-declaration/_config.js new file mode 100644 index 00000000000..ed47aec6333 --- /dev/null +++ b/test/function/samples/unused-for-loop-declaration/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'does not partially tree-shake unused declarations with side-effects in for loops' +}; diff --git a/test/function/samples/unused-for-loop-declaration/main.js b/test/function/samples/unused-for-loop-declaration/main.js new file mode 100644 index 00000000000..4f775356dca --- /dev/null +++ b/test/function/samples/unused-for-loop-declaration/main.js @@ -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');