@@ -14,6 +14,7 @@ export function emitStylesAndImports(args: {
1414 isAstNode : ( v : unknown ) => boolean ;
1515 objectToAst : ( j : any , v : Record < string , unknown > ) => any ;
1616 literalToAst : ( j : any , v : unknown ) => any ;
17+ stylesIdentifier : string ;
1718} ) : void {
1819 const {
1920 root,
@@ -26,6 +27,7 @@ export function emitStylesAndImports(args: {
2627 isAstNode,
2728 objectToAst,
2829 literalToAst,
30+ stylesIdentifier,
2931 } = args ;
3032
3133 // Preserve file header directives (e.g. `// oxlint-disable ...`). Depending on the parser/printer,
@@ -176,20 +178,18 @@ export function emitStylesAndImports(args: {
176178 }
177179 }
178180
179- // Insert stylex import at top (after existing imports, before code)
181+ // Insert stylex import at the very top of the file
182+ // We use unshift instead of inserting before first import because:
183+ // 1. The styled-components import might be removed, leaving mid-file imports as "first"
184+ // 2. Mid-file imports (like `import React` after declarations) should stay where they are
180185 const hasStylexImport =
181186 root . find ( j . ImportDeclaration , { source : { value : "@stylexjs/stylex" } } as any ) . size ( ) > 0 ;
182187 if ( ! hasStylexImport ) {
183- const firstImport = root . find ( j . ImportDeclaration ) . at ( 0 ) ;
184188 const stylexImport = j . importDeclaration (
185189 [ j . importNamespaceSpecifier ( j . identifier ( "stylex" ) ) ] ,
186190 j . literal ( "@stylexjs/stylex" ) ,
187191 ) ;
188- if ( firstImport . size ( ) > 0 ) {
189- firstImport . insertBefore ( stylexImport ) ;
190- } else {
191- root . get ( ) . node . program . body . unshift ( stylexImport ) ;
192- }
192+ root . get ( ) . node . program . body . unshift ( stylexImport ) ;
193193 }
194194
195195 // Re-attach preserved header comments to the first statement (preferably the stylex import).
@@ -460,10 +460,10 @@ export function emitStylesAndImports(args: {
460460 }
461461 }
462462
463- // Insert `const styles = stylex.create(...)` near top (after imports)
463+ // Insert `const styles = stylex.create(...)` (or stylexStyles if styles is already used) near top (after imports)
464464 const stylesDecl = j . variableDeclaration ( "const" , [
465465 j . variableDeclarator (
466- j . identifier ( "styles" ) ,
466+ j . identifier ( stylesIdentifier ) ,
467467 j . callExpression ( j . memberExpression ( j . identifier ( "stylex" ) , j . identifier ( "create" ) ) , [
468468 j . objectExpression (
469469 [ ...resolvedStyleObjects . entries ( ) ] . map ( ( [ k , v ] ) => {
0 commit comments