From a7c82bdfa98f6825143b7afba03d28d325e4a718 Mon Sep 17 00:00:00 2001 From: CPunisher <1343316114@qq.com> Date: Fri, 12 Jul 2024 21:03:50 +0800 Subject: [PATCH] fix(es/minifier): Fix variable declaration in default branch (#9220) **Description:** When a default branch appears before an exact match, the variable declaration should be recorded before deleting the default branch. **Related issue:** - Closes https://github.com/swc-project/swc/issues/8919 --- .../src/compress/optimize/switches.rs | 9 ++++++++- .../tests/fixture/issues/8919/input.js | 11 +++++++++++ .../tests/fixture/issues/8919/output.js | 2 ++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 crates/swc_ecma_minifier/tests/fixture/issues/8919/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/issues/8919/output.js diff --git a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs index 5b5dab03bcc0..95831bf6473b 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs @@ -86,7 +86,14 @@ impl Optimizer<'_> { if !may_match_other_than_exact { // remove default if there's an exact match - cases.retain(|case| case.test.is_some()); + cases.retain(|case| { + if case.test.is_some() { + true + } else { + var_ids.extend(case.cons.extract_var_ids()); + false + } + }); } if cases.len() == 2 { diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/8919/input.js b/crates/swc_ecma_minifier/tests/fixture/issues/8919/input.js new file mode 100644 index 000000000000..ca6d306f5b59 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/fixture/issues/8919/input.js @@ -0,0 +1,11 @@ +"use strict"; +const k = (() => { + switch ("") { + default: + var x; + case "": + x; + } + return x; +})(); +console.log(k); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/8919/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/8919/output.js new file mode 100644 index 000000000000..53588984737d --- /dev/null +++ b/crates/swc_ecma_minifier/tests/fixture/issues/8919/output.js @@ -0,0 +1,2 @@ +"use strict"; +console.log(void 0);