From 7edf30e259e3de7405ed299da32b8b19bb0f56e0 Mon Sep 17 00:00:00 2001 From: magic-akari Date: Mon, 6 Mar 2023 19:26:43 +0800 Subject: [PATCH] fix(es/transforms): Handle object shorthand prop in `const_modules` --- .../src/const_modules.rs | 22 +++++++++++++++++++ .../tests/const_modules.rs | 13 +++++++++++ 2 files changed, 35 insertions(+) diff --git a/crates/swc_ecma_transforms_optimization/src/const_modules.rs b/crates/swc_ecma_transforms_optimization/src/const_modules.rs index 763cd5ebb247..5137c055b884 100644 --- a/crates/swc_ecma_transforms_optimization/src/const_modules.rs +++ b/crates/swc_ecma_transforms_optimization/src/const_modules.rs @@ -197,4 +197,26 @@ impl VisitMut for ConstModules { } }; } + + fn visit_mut_prop(&mut self, n: &mut Prop) { + match n { + Prop::Shorthand(id) => { + if let Some(value) = self.scope.imported.get(&id.sym) { + *n = Prop::KeyValue(KeyValueProp { + key: id.take().into(), + value: Box::new((**value).clone()), + }); + return; + } + + if let Some(..) = self.scope.namespace.get(&id.to_id()) { + panic!( + "The const_module namespace `{}` cannot be used without member accessor", + id.sym + ) + } + } + _ => n.visit_mut_children_with(self), + } + } } diff --git a/crates/swc_ecma_transforms_optimization/tests/const_modules.rs b/crates/swc_ecma_transforms_optimization/tests/const_modules.rs index 7951ae0131e9..50d4beb35062 100644 --- a/crates/swc_ecma_transforms_optimization/tests/const_modules.rs +++ b/crates/swc_ecma_transforms_optimization/tests/const_modules.rs @@ -134,3 +134,16 @@ test!( })['var']; "# ); + +test!( + ::swc_ecma_parser::Syntax::default(), + |tester| tr(tester, &[("foo", &[("bar", "true")])]), + use_as_object_prop_shorthand, + r#" +import { bar } from 'foo'; +console.log({ bar }); +"#, + r#" +console.log({ bar: true }); +"# +);