From 9a309103a43175c0a41bd1865f44d2c60a3f36e9 Mon Sep 17 00:00:00 2001 From: IWANABETHATGUY Date: Sat, 14 Dec 2024 16:05:56 +0800 Subject: [PATCH] fix(oxc_transformer): inject_global_variables should considering string imported name (#7768) Co-authored-by: Boshen --- .../src/plugins/inject_global_variables.rs | 10 ++++++++-- .../plugins/inject_global_variables.rs | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/oxc_transformer/src/plugins/inject_global_variables.rs b/crates/oxc_transformer/src/plugins/inject_global_variables.rs index 12cce4078f618..1fae270abb14d 100644 --- a/crates/oxc_transformer/src/plugins/inject_global_variables.rs +++ b/crates/oxc_transformer/src/plugins/inject_global_variables.rs @@ -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, ) diff --git a/crates/oxc_transformer/tests/integrations/plugins/inject_global_variables.rs b/crates/oxc_transformer/tests/integrations/plugins/inject_global_variables.rs index 03835d70ed99a..140c8642ea52f 100644 --- a/crates/oxc_transformer/tests/integrations/plugins/inject_global_variables.rs +++ b/crates/oxc_transformer/tests/integrations/plugins/inject_global_variables.rs @@ -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