Skip to content

Commit

Permalink
feat: optional import attribute now accepts true as string literal
Browse files Browse the repository at this point in the history
  • Loading branch information
alekitto committed Nov 5, 2023
1 parent 24f4210 commit bb1cc2b
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 7 deletions.
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { compile, start, prepareStackTrace } from './pkg/compiler';
export { compile, isValidIdentifier, start, prepareStackTrace } from './pkg/compiler';

declare interface JsMethodParameter {
name?: String;
Expand Down
55 changes: 50 additions & 5 deletions src/parser/transformers/optional_import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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<dyn Fold> {
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 {
}
"#
);
}
}
2 changes: 1 addition & 1 deletion src/testing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit bb1cc2b

Please sign in to comment.