diff --git a/packages/babel-plugin-minify-simplify/__tests__/fixtures/eqnull/actual.js b/packages/babel-plugin-minify-simplify/__tests__/fixtures/eqnull/actual.js new file mode 100644 index 000000000..6858e7693 --- /dev/null +++ b/packages/babel-plugin-minify-simplify/__tests__/fixtures/eqnull/actual.js @@ -0,0 +1,3 @@ +x == undefined; +x == void 0; +x === undefined; diff --git a/packages/babel-plugin-minify-simplify/__tests__/fixtures/eqnull/expected.js b/packages/babel-plugin-minify-simplify/__tests__/fixtures/eqnull/expected.js new file mode 100644 index 000000000..9ef47da34 --- /dev/null +++ b/packages/babel-plugin-minify-simplify/__tests__/fixtures/eqnull/expected.js @@ -0,0 +1 @@ +x == null, x == null, x === undefined; \ No newline at end of file diff --git a/packages/babel-plugin-minify-simplify/src/index.js b/packages/babel-plugin-minify-simplify/src/index.js index 426634f69..7a1de9637 100644 --- a/packages/babel-plugin-minify-simplify/src/index.js +++ b/packages/babel-plugin-minify-simplify/src/index.js @@ -119,6 +119,13 @@ module.exports = ({ types: t }) => { ] }, + BinaryExpression(path) { + if (["!=", "=="].indexOf(path.node.operator) !== -1) { + undefinedToNull(path.get("left")); + undefinedToNull(path.get("right")); + } + }, + LogicalExpression: { exit: logicalExpression.simplifyPatterns }, @@ -1141,4 +1148,21 @@ module.exports = ({ types: t }) => { function isAncestor(path1, path2) { return !!path2.findParent(parent => parent === path1); } + + function isPureVoid(path) { + return path.isUnaryExpression({ operator: "void" }) && path.isPure(); + } + + function isGlobalUndefined(path) { + return ( + path.isIdentifier({ name: "undefined" }) && + !path.scope.getBinding("undefined") + ); + } + + function undefinedToNull(path) { + if (isGlobalUndefined(path) || isPureVoid(path)) { + path.replaceWith(t.nullLiteral()); + } + } }; diff --git a/packages/babel-plugin-transform-simplify-comparison-operators/src/index.js b/packages/babel-plugin-transform-simplify-comparison-operators/src/index.js index 28891b9f1..d543432b4 100644 --- a/packages/babel-plugin-transform-simplify-comparison-operators/src/index.js +++ b/packages/babel-plugin-transform-simplify-comparison-operators/src/index.js @@ -70,6 +70,7 @@ module.exports = function({ types: t }) { BinaryExpression(path) { const { node } = path; const op = node.operator; + if (op !== "===" && op !== "!==") { return; }