fix(oxc_transformer): inject_global_variables should considering string imported name (#7768)

Co-authored-by: Boshen <boshenc@gmail.com>
This commit is contained in:
IWANABETHATGUY 2024-12-14 16:05:56 +08:00 committed by GitHub
parent 9d77ab79f1
commit 9a309103a4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 26 additions and 2 deletions

View file

@ -5,6 +5,7 @@ use oxc_allocator::Allocator;
use oxc_ast::{ast::*, AstBuilder, NONE};
use oxc_semantic::{ScopeTree, SymbolTable};
use oxc_span::{CompactStr, SPAN};
use oxc_syntax::identifier;
use oxc_traverse::{traverse_mut, Traverse, TraverseCtx};
use super::{
@ -210,11 +211,16 @@ impl<'a> InjectGlobalVariables<'a> {
fn inject_import_to_specifier(&self, inject: &InjectImport) -> ImportDeclarationSpecifier<'a> {
match &inject.specifier {
InjectImportSpecifier::Specifier { imported, local } => {
let imported = imported.as_deref().unwrap_or("default");
let imported_name = imported.as_deref().unwrap_or("default");
let imported = if identifier::is_identifier_name(imported_name) {
self.ast.module_export_name_identifier_name(SPAN, imported_name)
} else {
self.ast.module_export_name_string_literal(SPAN, imported_name, None)
};
let local = inject.replace_value.as_ref().unwrap_or(local).as_str();
self.ast.import_declaration_specifier_import_specifier(
SPAN,
self.ast.module_export_name_identifier_name(SPAN, imported),
imported,
self.ast.binding_identifier(SPAN, local),
ImportOrExportKind::Value,
)

View file

@ -107,6 +107,24 @@ fn named() {
);
}
#[test]
fn string() {
let config = InjectGlobalVariablesConfig::new(vec![InjectImport::named_specifier(
"jquery",
Some("😊"),
"$",
)]);
test(
"$",
"
import { '😊' as $ } from 'jquery';
$
;
",
config,
);
}
#[test]
fn keypaths() {
// overwrites keypaths