From bb1cc2b93696840fbe74f2ed561b7ed0cecb878f Mon Sep 17 00:00:00 2001 From: Alessandro Chitolina Date: Sun, 5 Nov 2023 13:35:36 +0100 Subject: [PATCH] feat: optional import attribute now accepts true as string literal --- index.d.ts | 2 +- src/parser/transformers/optional_import.rs | 55 ++++++++++++++++++++-- src/testing/mod.rs | 2 +- 3 files changed, 52 insertions(+), 7 deletions(-) diff --git a/index.d.ts b/index.d.ts index cc43493..7df5a24 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,4 +1,4 @@ -export { compile, start, prepareStackTrace } from './pkg/compiler'; +export { compile, isValidIdentifier, start, prepareStackTrace } from './pkg/compiler'; declare interface JsMethodParameter { name?: String; diff --git a/src/parser/transformers/optional_import.rs b/src/parser/transformers/optional_import.rs index 6a6f42b..503bfb1 100644 --- a/src/parser/transformers/optional_import.rs +++ b/src/parser/transformers/optional_import.rs @@ -87,11 +87,10 @@ impl VisitMut for OptionalImport { .and_then(|p| p.as_key_value()) .map(|kv| { kv.key.as_ident().is_some_and(|i| i.sym == "optional") - && kv.value.as_lit().is_some_and(|l| { - let Lit::Bool(b) = l else { - return false; - }; - b.value + && kv.value.as_lit().is_some_and(|l| match l { + Lit::Bool(b) => b.value, + Lit::Str(s) => s.value.to_string() == "true", + _ => false, }) }) .unwrap_or(false) @@ -299,3 +298,49 @@ impl VisitMut for OptionalImport { ); } } + +#[cfg(test)] +mod tests { + use crate::parser::transformers::optional_import; + use crate::testing::compile_tr; + use swc_common::{chain, Mark}; + use swc_ecma_transforms_base::resolver; + use swc_ecma_visit::Fold; + + fn create_pass() -> Box { + let unresolved_mark = Mark::new(); + let top_level_mark = Mark::new(); + + Box::new(chain!( + resolver(unresolved_mark, top_level_mark, false), + optional_import(unresolved_mark), + )) + } + + #[test] + pub fn should_compile_optional_imports_correctly() { + let code = r#" +import Redis, { Cluster as RedisCluster } from 'ioredis' with { optional: 'true' }; +class RedisAdapter { +} +"#; + + let compiled = compile_tr(|_| create_pass(), code); + assert_eq!( + compiled, + r#"const _r = function() { + try { + return require("ioredis"); + } catch { + return void 0; + } +}(); +const Redis = void 0 !== _r ? _interop_require_default(_r, true).default : void 0; +const RedisCluster = _r?.Cluster; +; +class RedisAdapter { +} +"# + ); + } +} diff --git a/src/testing/mod.rs b/src/testing/mod.rs index 74798ff..994d6c0 100644 --- a/src/testing/mod.rs +++ b/src/testing/mod.rs @@ -49,7 +49,7 @@ where decorators: true, decorators_before_export: false, export_default_from: false, - import_attributes: false, + import_attributes: true, allow_super_outside_method: false, allow_return_outside_function: true, auto_accessors: true,