From c6b72831e30c2ce3c540488ebea65cbe4a546b10 Mon Sep 17 00:00:00 2001 From: echo094 <20028238+echo094@users.noreply.github.com> Date: Mon, 16 Oct 2023 18:55:27 +0800 Subject: [PATCH] visitor/calculate-binary: check if left and right are both constants before replacing Signed-off-by: echo094 <20028238+echo094@users.noreply.github.com> --- src/visitor/calculate-binary.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/visitor/calculate-binary.js b/src/visitor/calculate-binary.js index e871f6a..3b87d18 100644 --- a/src/visitor/calculate-binary.js +++ b/src/visitor/calculate-binary.js @@ -1,7 +1,18 @@ const generator = require('@babel/generator').default +const t = require('@babel/types') +/** + * Calculate BinaryExpression if left and right are both literals. + * Otherwise, the expression can't be simplified. + * + * For example, `typeof window` can be calculated but it's not constant. + */ module.exports = { BinaryExpression(path) { + const { left, right } = path.node + if (!t.isLiteral(left) || !t.isLiteral(right)) { + return + } const code = generator(path.node).code try { const ret = eval(code)