Skip to content

Commit

Permalink
Handle ClassDeclaration binding bug in babel
Browse files Browse the repository at this point in the history
+ (Fixes #365)

This is happening because ClassDeclarations have bindings in two scopes where as FunctionDeclarations have bindings only in the scope where it is defined.

+ babel bug: babel/babel#5156
  • Loading branch information
boopathi committed Feb 12, 2017
1 parent 8b86de0 commit 9e640ea
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -1129,4 +1129,24 @@ describe("mangle-names", () => {
`);
expect(transform(source)).toBe(expected);
});

it("should fix issue#365 - classDeclaration with unsafe parent scope", () => {
const source = unpad(`
function foo() {
eval("");
class A {}
class B {}
}
`);
expect(transform(source)).toBe(source);
});

it("should fix classDeclaration with unsafe program scope", () => {
const source = unpad(`
eval("");
class A {}
class B {}
`);
expect(transform(source, { topLevel: true })).toBe(source);
});
});
15 changes: 14 additions & 1 deletion packages/babel-plugin-minify-mangle-names/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,16 @@ module.exports = ({ types: t, traverse }) => {
Scopable(path) {
const {scope} = path;

if (!mangler.eval && hasEval(scope)) return;
if (!mangler.eval) {
if (hasEval(scope)) return;

// ClassDeclaration has binding in two scopes
// 1. The scope in which it is declared
// 2. The class's own scope
// So, when the scope.1 is an unsafeScope, mangling happens in scope.2
// To avoid that, we check if it's a class declaration
if (path.isClassDeclaration() && hasEval(path.parentPath.scope)) return;
}

if (mangler.visitedScopes.has(scope)) return;
mangler.visitedScopes.add(scope);
Expand Down Expand Up @@ -170,7 +179,11 @@ module.exports = ({ types: t, traverse }) => {
if (isTopLevel) {
mangler.rename(mangler.program.scope, oldName, next);
}

// mark the binding as renamed
// this is redundant and exists to work around a bug in babel
// ClassDeclarations have binding in two scopes
// - https://github.com/babel/babel/issues/5156
binding.renamed = true;
}
}
Expand Down

0 comments on commit 9e640ea

Please sign in to comment.