@@ -138,12 +138,11 @@ export default function i18nMessagesTransformer(
138138 return ( context : ts . TransformationContext ) => {
139139 const f = context . factory ;
140140
141- // Build window. i18next.t("hash") call
141+ // create i18next.t("hash") call
142142 const makeI18nextCall = ( hashId : string ) : ts . CallExpression => {
143- const windowIdent = f . createIdentifier ( "window" ) ;
144- const i18nextAccess = f . createPropertyAccessExpression ( windowIdent , "i18next" ) ;
145- const tAccess = f . createPropertyAccessExpression ( i18nextAccess , "t" ) ;
146- return f . createCallExpression ( tAccess , /*typeArgs*/ undefined , [ f . createStringLiteral ( hashId ) ] ) ;
143+ const i18nextIdent = f . createIdentifier ( "i18next" ) ;
144+ const tAccess = f . createPropertyAccessExpression ( i18nextIdent , "t" ) ;
145+ return f . createCallExpression ( tAccess , undefined , [ f . createStringLiteral ( hashId ) ] ) ;
147146 } ;
148147
149148 const visitNode : ts . Visitor = ( node ) => {
@@ -214,6 +213,37 @@ export default function i18nMessagesTransformer(
214213 return ts . visitEachChild ( node , visitNode , context ) ;
215214 } ;
216215
217- return ( sf : ts . SourceFile ) => ts . visitNode ( sf , visitNode ) ;
216+ // return (sf: ts.SourceFile) => ts.visitNode(sf, visitNode);
217+ return ( sf : ts . SourceFile ) => {
218+ // 1️⃣ Check if "import i18next from 'i18next'" already exists
219+ const alreadyImported = sf . statements . some (
220+ ( stmt ) =>
221+ ts . isImportDeclaration ( stmt ) &&
222+ stmt . moduleSpecifier &&
223+ ts . isStringLiteral ( stmt . moduleSpecifier ) &&
224+ stmt . moduleSpecifier . text === "i18next"
225+ ) ;
226+
227+ // 2️⃣ Visit and transform nodes as before
228+ let updated = ts . visitNode ( sf , visitNode ) ;
229+
230+ // 3️⃣ If missing, prepend a new import
231+ if ( ! alreadyImported ) {
232+ const importDecl = f . createImportDeclaration (
233+ undefined ,
234+ undefined ,
235+ f . createImportClause (
236+ false , // isTypeOnly
237+ f . createIdentifier ( "i18next" ) , // default import name
238+ undefined
239+ ) ,
240+ f . createStringLiteral ( "i18next" )
241+ ) ;
242+
243+ updated = f . updateSourceFile ( updated , [ importDecl , ...updated . statements ] ) ;
244+ }
245+
246+ return updated ;
247+ } ;
218248 } ;
219249}
0 commit comments