From bda4c1d1846a484f3f4af714cbef0ac9ef2a174c Mon Sep 17 00:00:00 2001 From: Boopathi Rajaa Date: Thu, 3 Nov 2016 00:30:17 +0100 Subject: [PATCH] Fix path.evaluate for runtime errors in constant-folding (close #245) --- .../__tests__/constant-folding-test.js | 11 +++++++++++ .../src/index.js | 13 ++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/babel-plugin-minify-constant-folding/__tests__/constant-folding-test.js b/packages/babel-plugin-minify-constant-folding/__tests__/constant-folding-test.js index 9d54194b1..30fe72afc 100644 --- a/packages/babel-plugin-minify-constant-folding/__tests__/constant-folding-test.js +++ b/packages/babel-plugin-minify-constant-folding/__tests__/constant-folding-test.js @@ -49,4 +49,15 @@ describe("constant-folding-plugin", () => { `); expect(transform(source)).toBe(expected); }); + + it("should handle runtime errors", () => { + const source = unpad(` + try { + x({ + toString: 0 + } + ''); + } catch (e) {} + `); + expect(transform(source)).toBe(source); + }); }); diff --git a/packages/babel-plugin-minify-constant-folding/src/index.js b/packages/babel-plugin-minify-constant-folding/src/index.js index da4865a08..4462037bc 100644 --- a/packages/babel-plugin-minify-constant-folding/src/index.js +++ b/packages/babel-plugin-minify-constant-folding/src/index.js @@ -92,7 +92,7 @@ module.exports = ({ types: t, traverse }) => { return; } - const res = path.evaluate(); + const res = evaluate(path); if (res.confident) { // Avoid fractions because they can be longer than the original expression. // There is also issues with number percision? @@ -118,3 +118,14 @@ module.exports = ({ types: t, traverse }) => { }, }; }; + +function evaluate(path) { + try { + return path.evaluate(); + } catch (e) { + return { + confident: false, + error: e + }; + } +}