Skip to content

Commit bee7950

Browse files
committed
Add SWC plugin imports after "use client" directive (dotansimha#9445)
When adding a "use client" directive to a module, it must come before any other expressions. Instead of always inserting import declarations as the first item, the SWC plugin now checks if the first expression in a module's body is a "use client" directive and inserts its imports after it, if that's the case. Closes: dotansimha#9445
1 parent ab4b03e commit bee7950

File tree

1 file changed

+12
-1
lines changed
  • packages/presets/swc-plugin/src

1 file changed

+12
-1
lines changed

packages/presets/swc-plugin/src/lib.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use swc_core::{
66
common::Span,
77
ecma::{
88
ast::*,
9+
atoms::atom,
910
utils::quote_ident,
1011
visit::{as_folder, FoldWith, VisitMut, VisitMutWith},
1112
},
@@ -179,9 +180,19 @@ impl VisitMut for GraphQLVisitor {
179180

180181
let platform_specific_path = self.get_relative_import_path("graphql");
181182

183+
// Add import after any "use client" directive, since it must come before any other expression
184+
let mut index = 0;
185+
if let ModuleItem::Stmt(Stmt::Expr(ExprStmt { expr, .. })) = &module.body[0] {
186+
if let Expr::Lit(Lit::Str(Str { value, .. })) = &**expr {
187+
if atom!("use client") == *value {
188+
index = 1;
189+
}
190+
}
191+
}
192+
182193
for operation_or_fragment_name in &self.graphql_operations_or_fragments_to_import {
183194
module.body.insert(
184-
0,
195+
index,
185196
ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
186197
span: Default::default(),
187198
specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier {

0 commit comments

Comments
 (0)