Skip to content

Commit

Permalink
Fix var hoisting bug in DCE
Browse files Browse the repository at this point in the history
Fix bug where var declarations after compleition statements are
deadcode eliminated - vars are hoisted in JS and need to be preserved
like function declarations

(Close #167)
  • Loading branch information
boopathi committed Sep 29, 2016
1 parent 32c809b commit 1610012
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1999,4 +1999,39 @@ describe("dce-plugin", () => {
const expected = source;
expect(transform(source)).toBe(expected);
});

it("should preserve variabledeclarations(var) after completion statements", () => {
const source = unpad(`
function foo() {
a = 1;
return a;
var a;
}
`);

const expected = source;

expect(transform(source)).toBe(expected);
});

it("should NOT preserve variabledeclarations(let) after completion statements", () => {
const source = unpad(`
function foo() {
a = 1;
b = 2;
return a + b;
let a, b;
}
`);

const expected = unpad(`
function foo() {
a = 1;
b = 2;
return a + b;
}
`);

expect(transform(source)).toBe(expected);
});
});
10 changes: 8 additions & 2 deletions packages/babel-plugin-minify-dead-code-elimination/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ module.exports = ({ types: t, traverse }) => {
continue;
}

if (purge && !p.isFunctionDeclaration()) {
if (purge && !canExistAfterCompletion(p)) {
removeOrVoid(p);
}
}
Expand All @@ -299,7 +299,7 @@ module.exports = ({ types: t, traverse }) => {

// Not last in it's block? (See BlockStatement visitor)
if (path.container.length - 1 !== path.key &&
!path.getSibling(path.key + 1).isFunctionDeclaration() &&
!canExistAfterCompletion(path.getSibling(path.key + 1)) &&
path.parentPath.isBlockStatement()
) {
// This is probably a new oppurtinity by some other transform
Expand Down Expand Up @@ -900,4 +900,10 @@ module.exports = ({ types: t, traverse }) => {
};
}
}

// things that are hoisted
function canExistAfterCompletion(path) {
return path.isFunctionDeclaration()
|| path.isVariableDeclaration({ kind: "var" });
}
};

0 comments on commit 1610012

Please sign in to comment.