Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

avoid transforming side effecty member expression checks[fix #469] #506

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -178,4 +178,16 @@ describe("guarded-expressions-plugin", () => {
);
expect(transform(source)).toBe(source);
});

it("should not minify side effecty member expression checks", () => {
let source = unpad(
`
{
var a = {};
}
var b = a && a[foo];
`
);
expect(transform(source)).toBe(source);
});
});
37 changes: 36 additions & 1 deletion packages/babel-plugin-minify-guarded-expressions/src/index.js
@@ -1,8 +1,39 @@
"use strict";

function getBlockPath(path) {
var parent = path.findParent(function(p) {
return p.isBlockStatement();
});
// return program path if null
return parent !== null ? parent : path.getFunctionParent();
}

module.exports = function({ types: t }) {
const flipExpressions = require("babel-helper-flip-expressions")(t);

// identify defined check patterns like a && a.foo
// a && a['foo']
// should bail in this case if declaration is inside other block
function isDefinedCheck(path, left, right) {
if (t.isIdentifier(left) && t.isMemberExpression(right)) {
const binding = path.scope.getBinding(left.node.name);
// should bail only for var
if (binding === null || binding.kind !== "var") {
return false;
}
const expressionParent = getBlockPath(path);
const bindingParent = getBlockPath(binding.path);
// bail if referenced in the same block
if (expressionParent !== bindingParent) {
return true;
}

const { object } = right.node;
return left.node.name !== object.name;
}
return false;
}

return {
name: "minify-guarded-expressions",
visitor: {
Expand Down Expand Up @@ -32,7 +63,11 @@ module.exports = function({ types: t }) {
if (leftTruthy === false) {
// Short-circuit
path.replaceWith(node.left);
} else if (leftTruthy === true && left.isPure()) {
} else if (
leftTruthy === true &&
left.isPure() &&
!isDefinedCheck(path, left, right)
) {
path.replaceWith(node.right);
} else if (
right.evaluateTruthy() === false &&
Expand Down