<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alex Batalov on Medium]]></title>
        <description><![CDATA[Stories by Alex Batalov on Medium]]></description>
        <link>https://medium.com/@radist2s?source=rss-24616a5c3cd3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lqYylkwcISRwa_IgMDxklQ.jpeg</url>
            <title>Stories by Alex Batalov on Medium</title>
            <link>https://medium.com/@radist2s?source=rss-24616a5c3cd3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 17:09:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@radist2s/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[One Command, One Day, Multiple Languages: Our Migration from react-i18next to LinguiJS]]></title>
            <link>https://medium.com/@radist2s/one-command-one-day-multiple-languages-our-migration-from-react-i18next-to-linguijs-4b07ac73a9bb?source=rss-24616a5c3cd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b07ac73a9bb</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[i18n]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[i18next]]></category>
            <category><![CDATA[localization]]></category>
            <dc:creator><![CDATA[Alex Batalov]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 21:36:48 GMT</pubDate>
            <atom:updated>2025-01-29T22:04:07.988Z</atom:updated>
            <content:encoded><![CDATA[<h3>How We Migrated a Large React Application from react-i18next to LinguiJS in 1 Day</h3><p>Navigating the world of application development involves many crucial decisions, one of which is selecting the right tools for your localization needs.</p><p>What if I told you that you can translate your own application into any language <em>in just one minute with a single command?</em></p><p>A few months ago, our team of frontend developers at <a href="https://monite.com/">Monite</a> were faced with the task of migrating our React application from react-i18next to LinguiJS. We achieved the following results:</p><ul><li>Convenient support for application translations through an easy interface; the ability to delegate the responsibility for maintaining the relevance of translations to an external team</li><li>Simple ability for app localization without compromising the developer experience, the possibility to use regular JSX as a translation string</li><li>The ability to translate the application into any language in just one minute with a single command</li></ul><p>But hold on, we’re forgetting (probably) the coolest thing about this migration: we did all this in just one day. Sounds too good to be true, right?</p><p>While our journey had its share of challenges, we have mapped out a path that you can follow to avoid the problems that we faced.</p><p>In this article, we will share our experience, provide ready-made recipes, transformers for jscodeshift, and custom ESLint rules to make your migration process as smooth as possible.</p><h3>The limitations of i18next</h3><p>Alright, so picture this: our app was growing like crazy, and we knew we had to translate it into a bunch of different languages, pronto. To get this done, we were using the i18next library, specifically the React version, react-i18next. But as we dug in, it was clear that it had some serious limitations that were hard to ignore.</p><p>Here are the primary issues we faced when working with i18next:</p><h4>1. Lack of semantic meaning in dictionary keys</h4><p>With i18next, translation keys are generally based on the structure of your JSON language files. For example:</p><pre>{<br>  &quot;look&quot;: {<br>    &quot;deep&quot;: &quot;Look deep&quot;<br>  }<br>}</pre><p>To employ this translation in your app, you would execute something like:</p><pre>i18next.t(&#39;look.deep&#39;);</pre><p>The big problem with this approach is that keys like look.deep have no semantic meaning. They don&#39;t tell the developer anything about what they&#39;re actually translating, unless they go hunting through the language files. This <em>lack of context</em> becomes particularly problematic in larger codebases, leading to unnecessary cognitive load and potential mistakes.</p><h4>2. Inefficient codebase search</h4><p>If you have a message displayed in your app’s interface, and you want to find where that string is defined or used in your code, it can be a real headache. Without a meaningful key or context, it can take ages to track down the relevant piece of code.</p><h4>3. JSON format is not translation-friendly</h4><p>While JSON is a widely accepted data interchange format, it’s not the most intuitive format for translators. This is the case for a few reasons:</p><ul><li><strong>Complex Pluralization:</strong> Pluralization translation in i18next can be quite convoluted, especially for languages with complex plural rules.</li><li><strong>Lack of Usage Indicators:</strong> There is no way to quickly find out in which parts of the application the translation string is used and how many times. Its search is tiring and time-consuming.</li><li><strong>No Commenting Ability:</strong> JSON dictionaries of i18next doesn&#39;t support comments, making it impossible for developers to leave notes or explanations for translators. Thejson5 doesn&#39;t solve this problem either.</li></ul><p>i18next is a powerful library for managing translations in JavaScript, but we found that its limitations were hindering the growth of our application. It became clear that we needed a more <em>efficient</em> and <em>scalable</em> solution for localization.</p><p>That’s why we chose LinguiJS.</p><blockquote><em>It’s worth mentioning that there’s another library for localization — </em><em>react-intl. In my opinion, it&#39;s better designed than </em><em>react-i18next, has its advantages, but still falls short of LinguiJS due to the absence in </em><em>react-intl of something comparable to the</em><em>&lt;Trans/&gt; Component from </em><em>@lingui/macro.</em></blockquote><h3>The advantages of LinguiJS</h3><p>Let’s break down why LinguiJS quickly became our localization library of choice:</p><h4>1. Semantic keys</h4><p>In contrast to i18next, LinguiJS uses the actual message string as the key. This offers a more intuitive approach - developers and translators can directly understand the context of the translation without needing to refer to the language files.</p><p>Consider this example:</p><pre>import {t} from &quot;@lingui/macro&quot;;<br><br>t`Look deep`;</pre><p>Here, the string “Look deep” is both the key and the default message. This feature improves the readability of the code and offers a smoother translation process.</p><h4>2. Automatic extraction of messages</h4><p>With LinguiJS, developers can automatically extract messages from the source code into PO and POT files, a widely-used format for handling multilingual data.</p><p>If you’re scratching your head thinking, “PO files? Isn&#39;t that something for WordPress and PHP, Alex? Are you sure about this?”</p><p>Okay, let’s hold on for just a sec. Allow me to explain.</p><p>These PO (Portable Object) and POT (PO Template) files are part of the <a href="https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html">Gettext</a> system, a standard that has been around since the &#39;90s, with a grand history and wide adoption in the localization industry.</p><p>The LinguiJS function for automatically extracting messages from the source code into PO files eliminates the need for manually managing translation files, making the development process significantly more efficient.</p><p>By handling these traditional — but powerful — formats automatically, LinguiJS bridges the gap between the proven methods of the past and today’s modern development needs.</p><h4>3. The power of macros</h4><p>LinguiJS leverages Babel macros (by the way, we use <a href="https://lingui.dev/ref/swc-plugin">SWC plugin</a> — which is also available). These offer several powerful macros like t, Trans, Plural, etc.</p><p>Each of these macros is designed to solve a specific localization problem, making the translation process efficient and precise.</p><p>For example, Trans allows translations right within your JSX:</p><pre>import {Trans} from &quot;@lingui/macro&quot;;<br><br>&lt;Trans&gt;<br>    Look deep,<br>    &lt;strong&gt;my friend&lt;/strong&gt;<br>    &lt;Icon/&gt;<br>&lt;/Trans&gt;</pre><p>will be extracted as Look deep, &lt;0&gt;my friend&lt;/0&gt;&lt;1/&gt; and will be translated as a single message.</p><h4>4. Superior pluralization syntax</h4><p>LinguiJS provides a simpler and more intuitive syntax for pluralization, thanks to its support for the <a href="https://cldr.unicode.org/index/cldr-spec/plural-rules">ICU MessageFormat</a> — an industry standard for complex translations.</p><p>Let’s take a look at the following example:</p><pre>import {t, plural} from &quot;@lingui/macro&quot;;<br><br>const itemCount = 2<br><br>t`You have ${plural(itemCount, {<br>    one: &#39;# item&#39;,<br>    other: &#39;# items&#39;,<br>})} in your cart`</pre><p>In this case, the template literal within the t macro is transformed into an ICU message syntax, and the string for translation becomes:</p><pre>#: src/app.tsx:5<br>msgid &quot;You have {itemCount, plural, one {# item} other {# items}} in your cart&quot;<br>msgstr &quot;&quot;</pre><p>Using this approach, we have a concise way to handle pluralization — while adhering to the correct grammatical rules for different languages.</p><blockquote><em>Most translation services understand ICU MessageFormat, so even such complex translations can be done automatically.</em></blockquote><h4>5. Easy handling of dates and numbers localization</h4><p>Forget about heavy libraries <em>like date-fns</em>! LinguiJS offers simple functions like i18n.date(...) and i18n.number(...) These work directly with the browser&#39;s built-in Intl.DateTimeFormat and Intl.NumberFormat.</p><p>You will be able to format date and time, and numbers, currencies using the built-in LinguiJS utils.</p><h4>6. Seamless integration with tools and services</h4><p>LinguiJS can be easily integrated with various translation services like:</p><ul><li><a href="https://translation.io/">translation.io</a></li><li><a href="https://crowdin.com/">Crowdin</a></li><li><a href="https://localise.biz/">Loco</a></li></ul><p>This ensures that you’re not tied to a specific vendor, and therefore provides more flexibility.</p><h3>Preparing for migration</h3><p>It’s worth starting with the fact that at the time of the migration, we already had about 600 tokens for translation.</p><p>We only supported the English language with a single JSON file, which was used by i18next for translations. But even if we had existing translations in other languages, converting them to the PO format would have been a piece of cake.</p><p>At one of the meetings, I joked that <em>I would migrate the application to LinguiJS in 1 working day</em>.</p><p>I had no idea how close this was to the truth.</p><p>The labor costs for manual refactoring in such cases can be quite high. Yes, you can do it if you’ve got a lot of time to spend, but you’ll definitely make mistakes when inserting key values from translation files.</p><p>All I can say is <em>“Good luck with the Merge Request!”</em></p><p>So how did I move forward?</p><ul><li>After some Googling, I didn’t find a tool for automatic migration from react-i18next to LinguiJS.</li><li>In the past, I’ve already written a couple of transformers for <a href="https://github.com/facebook/jscodeshift">JSCodeshift</a>, so I already knew what to do.</li><li>First, I determined what needed to be migrated automatically, and what was reasonably migrated manually.</li><li>There were a couple of places using the &lt;Trans/&gt; Component from react-i18next, and a little pluralization - this was easier to refactor the old-fashioned way.</li></ul><p>The overwhelming majority of translations were used within the i18next.t function and looked something like this:</p><pre>i18next.t(&#39;key:subkey1&#39;)<br>i18next.t(&#39;key:subkey2&#39;, { type })<br>i18next.t(&#39;key:subkey3&#39;, { foo: bar() })</pre><p>Such code will be migrated automatically.</p><p>The transformer for jscodeshift will need to convert our TypeScript code into the following form:</p><pre>t`Key Source 1`<br>t`Key ${type} Source 2`<br>t`Key ${bar()} Source 3`</pre><p>It will also be necessary to add imports for t from @lingui/macro and remove the imports of react-i18next and its Hooks (note: we didn&#39;t use i18next directly).</p><p>Some people may write transformers for jscodeshift every day, but for me it&#39;s not the easiest task - even with <a href="https://astexplorer.net/">AST Explorer</a> available. You need to stick around in the debugger to see the transformation results at all stages, deal with different types of nodes…</p><p>It’s exhausting, to say the least.</p><p>In principle, no one would have shot me suspicious glances if I’d spent a week or even two on the migration.</p><p>But, remember that challenge I decided to set for myself (or joke that I made, depending on how this turned out)?</p><p>I had five hours left. Ok, ChatGPT…</p><h3>Writing a transformer for jscodeshift</h3><p>At Monite, we actively use everything that the AI world offers us.</p><p>For example, during complex meetings, we use <a href="https://tactiq.io/">Tactiq</a> for automatic transcription and the creation of AI-summaries. Not to mention the use of ChatGPT and GitHub Copilot in daily development.</p><pre>ChatGPT, write me a transformer<br>for jscodeshift (esm) that would convert<br>all functions i18next.t(&#39;some.key&#39;) to t`some.key`.</pre><p>Right after the first message, it was clear that I would likely be assisting ChatGPT rather than the other way around. If you use ChatGPT often, you’d probably be familiar with the way that turns out.</p><p>Twenty minutes later, I received the first prototype of the transformer. It read the translation values from the JSON file i18next by keys and inserted them into the code, replacing t(&#39;key&#39;) with the Literal Template t:</p><pre>-i18next.t(&#39;some.key&#39;)<br>+t`Key Source 1`</pre><p>It was a stunning success! True, there were still a bunch of places in the code where values are passed to t for replacement: t(&#39;key:subkeyWithTypeReplace&#39;, { type }), as well as a lot of this mess:</p><pre>const foo = `${t(&#39;key1&#39;)} ${name} ${t(&#39;key2&#39;)}`</pre><p>Which, in my opinion, should have been transformed into this form:</p><pre>const foo = t`Key1Source ${name} Key2Source`</pre><p>I still had a whole 4.5 hours left until the end of the challenge, and I could have finished the migration manually, but I was already on a roll.</p><p><em>“Together we will move mountains!”</em> Pure euphoria! Legally!</p><p>Sometimes ChatGPT got a bit confused, and I had to create separate chats to solve corner cases, but we did it!</p><p>Another couple of hours, and the <a href="https://github.com/team-monite/i18next-to-lingui-jscodeshift-tranformer/blob/main/replace-i18n-next-with-lingui-t-macro-transformer.ts">final version of the transformer</a> was ready.</p><p>I spent the remaining time on validation of results and manual refactoring. I created an MR, changed the status of the task to In Review.</p><p>Success!</p><h3>The honeymoon’s over</h3><p>We’ve strayed a bit from the subject, the main hero of this story — LinguiJS.</p><p>As soon as our team started using LinguiJS, we appreciated how convenient it became to work with translations:</p><ul><li>No need to keep track of keys anymore: you run the command lingui extract and PO files will be automatically updated with new values.</li><li>Translations for deleted keys will be commented out, but not completely deleted — if these keys return in the future, the translations for them will simply be uncommented back.</li></ul><p>Brilliant, isn’t it?</p><p>PO files even look professional: IDEA supports highlighting of PO and POT files out of the box, and VSCode will suggest installing a plugin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a2aE1e336VUipj543V4_Fg.png" /><figcaption>PO files syntax highlighting</figcaption></figure><p>Time went on, everything was fine, but we started to notice that sometimes translations were not displayed. After a quick investigation, it became clear that you cannot use t at the module level.</p><p>Today, this is already fixed in the <a href="https://lingui.dev/tutorials/react-patterns#translations-outside-react-components">LinguiJS documentation</a>, but when we encountered this problem back then, it wasn’t as obvious.</p><p>No big deal. In our case moving t inside functions was not a problem - translations were mainly used inside React Components and Hooks.</p><p>I also wrote a <a href="https://github.com/team-monite/monite-sdk/blob/main/packages/eslint-plugin/lib/rules/lingui-no-top-level-t-macro.js">custom rule for ESLint</a> (of course, not by myself again), to prevent the use of t outside functions. It&#39;s easier to explicitly forbid something than to spend time on Code Review later.</p><blockquote><em>Community can already offer me an alternative: </em><a href="https://github.com/lingui/eslint-plugin"><em>several cool ESLint rules for LinguiJS</em></a><em> (we are planning to migrate to this package and remove our own solution).</em></blockquote><p>It seemed like this was the last nuance we missed during the migration, but…</p><h3>Jira: “Localization does not work in real time after changing locale”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*IUK2H6tP8wvJJxERRePgBw.gif" /><figcaption>Demonstration of a bug with language switching</figcaption></figure><p>This is where I received a task from our product owner: <em>changing the language only works the second time</em>.</p><p>It took me a little time to make sure that the problem was not in our code. I dug into the compilation result of the t macro. How surprised I was that I didn&#39;t understand its mechanism at all!</p><p>Inside React Components, t <em>does not directly use</em> the value of the I18nProvider context.</p><p>To instantly display another translation when changing the language, you need to add the useLingui() Hook inside the Component.</p><p>You don’t even have to use the return result of the Hook — just subscribe the Component to changes in the I18nProvider context.</p><p>I found that &lt;Trans/&gt;, &lt;Plural/&gt;, and other Components from the @lingui/macro package are regular React Components during compilation, and already use the useLingui() Hook inside.</p><p>Again, <a href="https://lingui.dev/tutorials/react-patterns#element-attributes-and-string-only-translations">everything is in the documentation</a> to be viewed.</p><p>I didn’t like the idea of <em>just subscribing to the Component with a Hook</em>. That’s exactly why the ability exists to pass an I18n instance for the t macro:</p><pre>-t`Hello, World!`<br>+const { i18n } = useLingui()<br>+t(i18n)`Hello, World!`</pre><p>Yes, with currying, it’s not as elegant as just single t, but at least all developers will understand what&#39;s happening inside the Component.</p><p>Also, the i18n variable can be passed to other functions (not Hooks) that previously used the t macro.</p><p>After discussing the difficulties in fixing the bug with the product owner, we agreed that <em>it’s not such a big problem</em> for the application right now. I suggested postponing the bug fix until the next sprint, keeping in mind that I could solve this task while working on another project — my own.</p><h3>LinguiJS and Server Side Rendering</h3><p>In the spring, I launched my own startup: <a href="https://artm.store/">NextGen Art Marketplace</a>. Only originals! No damn NFTs! Only physical Art!</p><p><em>Hey, Alex, slow down</em>.</p><p>For this project, I’m using Next.js with <a href="https://nextjs.org/docs/pages/building-your-application/rendering/server-side-rendering">SSR</a>. Realizing that the t macro can&#39;t provide stable operation for SSR due to asynchrony, I decided not to drag it out — and as part of the tasks for my project — I wrote another transformer, which curries the t macro with i18n variable from useLingui() Hook.</p><p>ChatGPT easily handled the task again, and within one hour I had a transformer that converts this code:</p><pre>t`Hello!`<br>t`Hello, ${name}!`<br>t`Hello, ${name}! (${counter + 1})`</pre><p>into this:</p><pre>const { i18n } = useLingui()<br>t(i18n)`Hello!`<br>t(i18n)`Hello, ${name}!`<br>t(i18n)`Hello, ${name}! (${counter + 1})`</pre><p>If t macro is used inside a React Component or Hook, the code const { i18n } = useLingui() will be automatically added at the beginning of the function.</p><blockquote><em>I updated the </em><a href="https://github.com/team-monite/i18next-to-lingui-jscodeshift-tranformer/tree/main#currying-of-t-macro"><em>transformer</em></a><em> I mentioned earlier, and added the option</em><em>--with-currying-of-t-macro true to it so that you can immediately migrate to the </em><em>t macro with currying.</em></blockquote><p>If t is used outside a React Component, for example inside a regular function, you will have to make it a Hook first, or pass i18n as an argument yourself after working with jscodeshift.</p><p>Let’s get back to product tasks: our goal is to fix translations in Next.js.</p><p>Loading LinguiJS translations for SSR is another place where I initially made mistakes.</p><p>First, I loaded the translations inside the App.getInitialProps() function using i18n from @lingui/core:</p><pre>import {i18n} from &#39;@lingui/core&#39;<br>// ⚠️ Wrong! There may be an error in SSR due to its async nature<br>i18n.load(locale, messages)</pre><p>I was lucky that I only had one language. Otherwise, due to being asynchronous, some parts of the application could be displayed during the rendering of dynamic Components in one language, and others in another.</p><p>I also passed the translations as properties to the App Component. This works, but then you will send the same translation strings to the client over and over again when navigating to a new page.</p><p>To load translations only once and cache them, I use dynamic imports for providers with translations. They will automatically be chunked, and will only be loaded when they are really needed.</p><p>Here’s what it looks like:</p><pre>// locale/ka/MessagesProvider.tsx<br><br>import {setupI18n} from &#39;@lingui/core&#39;;<br>import {I18nProvider} from &#39;@lingui/react&#39;;<br>import {ReactNode, useState} from &#39;react&#39;;<br>import {messages} from &#39;./messages&#39;; // Georgian(&#39;ka&#39;) translations<br><br>export default function MessagesProvider({children}: { children: ReactNode }) {<br>  const [i18n] = useState(() =&gt;<br>    setupI18n({<br>      locale: &#39;ka&#39;,<br>      locales: [&#39;ka&#39;, &#39;en&#39;], // &#39;en&#39; is a fallback for `Intl.*` or `messages.en` if specified<br>      messages: {<br>        [&#39;ka&#39;]: messages,<br>      },<br>    })<br>  );<br><br>  return &lt;I18nProvider i18n={i18n}&gt;{children}&lt;/I18nProvider&gt;;<br>}</pre><p>The setupI18n(...) function from @lingui/core creates an instance of the I18n class, and leaves i18n from@lingui/core untouched.</p><p>Using a dynamic provider with translations inside _app.tsx might look like this:</p><pre>// _app.tsx<br><br>import dynamic from &#39;next/dynamic&#39;;<br><br>const MessagesProviders = {<br>  en: dynamic(() =&gt; import(&#39;./locale/en/MessagesProvider&#39;)),<br>  ka: dynamic(() =&gt; import(&#39;./locale/ka/MessagesProvider&#39;)),<br>};<br><br>function App({Component, router, pageProps}) {<br>  const MessageProvider = MessagesProviders[router.locale]<br>  <br>  return (<br>    &lt;MessageProvider&gt;<br>      &lt;Component {...pageProps} /&gt;<br>    &lt;/MessageProvider&gt;<br>  );<br>}</pre><h3>Dynamic translations</h3><p>An important part of the Monite product is <a href="https://docs.monite.com/docs/drop-in-components">Drop-in</a> Web Component.</p><p>This Web Component can be embedded into any HTML page or any framework and allows you to get First-Class Bill Pay for your Neo-Bank’s clients in 15 minutes (if you have a Neo-Bank, of course).</p><p>I’ll talk about how we wrapped our React application in a Web Component and made it work inside Shadow DOM next time.</p><p>But for now, let’s get back to translations.</p><p>For our clients, we have to provide the ability to translate their interface into any language on the fly without running the lingui compile command.</p><p>We allow translations to be passed into the Web Component via the locale slot:</p><pre>&lt;monite-app api-url=&quot;https://api.monite.com/v1&quot;&gt;<br>  &lt;script slot=&quot;locale&quot; type=&quot;application/json&quot;&gt;<br>    { &quot;messages&quot;: { &quot;Counterpart&quot;: &quot;Gegenstück&quot; }, &quot;code&quot;: &quot;ge&quot; }<br>  &lt;/script&gt;<br>&lt;/monite-app&gt;</pre><p>The problem is that LinguiJS from Version 4 uses <a href="https://lingui.dev/releases/migration-4#hash-based-message-id-generation-and-context-feature">key hashing</a>.</p><p>After compilation ( lingui compile), the translation file loaded by the browser will look something like this:</p><pre>{ &quot;OVaF9k&quot;: &quot;Hello {name}&quot; }</pre><blockquote><em>Hashing </em><em>msgid significantly reduces the size of the final translation file but is only done for </em><em>t, </em><em>&lt;Trans/&gt;, and other Components from</em><em>@lingui/macro, not for </em><em>i18n._() from the </em><em>useLingui() Hook.</em></blockquote><p>To preserve dynamic translations, we would have to abandon the use of &lt;Trans/&gt; or &lt;Plural /&gt;, which we didn&#39;t want to do. After all, it&#39;s a killer feature of LinguiJS.</p><p>We will <strong>hash translation keys</strong> right <strong>in the browser!</strong></p><p>You can see how the hash is formed in the <a href="https://github.com/lingui/js-lingui/blob/main/packages/message-utils/src/generateMessageId.ts">LinguiJS source code</a>.</p><p>I think you’ve already guessed that I didn’t rewrite this function for browser compatibility myself. Yep, I got lazy.</p><p>For dynamic translations, all that remains is to pre-process the contents of the locale slot through the key hashing function and parse the ICU MessageFormat using compileMessage() from the @lingui/message-utils package.</p><pre>import {compileMessage} from &#39;@lingui/message-utils/compileMessage&#39;;<br>import {messages as messagesEn} from &#39;./messages&#39;;<br><br>export async function compileLinguiDynamicMessages(plainMessages: Record&lt;string, string&gt;) {<br>  const compiledMessages: Record&lt;string, unknown&gt; = {};<br><br>  for (const [key, value] of Object.entries(plainMessages)) {<br>    const compiledMessage = compileMessage(key || value);<br>    compiledMessages[await generateLinguiMessageId(key)] = compiledMessage; // generate key hash for `&lt;Trans/&gt;`, `&lt;Plural/&gt;` etc.<br>    compiledMessages[key] = compiledMessage; // keep original key for use in `i18n._()`<br>  }<br><br>  return {<br>    ...messagesEn,<br>    ...compiledMessages<br>  }<br>}<br><br>async function generateLinguiMessageId(messageId: string, context = &#39;&#39;) {<br>  const encoder = new TextEncoder();<br>  // For example, I omitted the `context` consideration from the implementation of `compileLinguiDynamicMessages`,<br>  // but you should remember that they also a part of the hash<br>  const data = encoder.encode(messageId + &#39;\u001F&#39; + (context || &#39;&#39;));<br>  const hashBuffer = await crypto.subtle.digest(&#39;SHA-256&#39;, data);<br>  const hashArray = Array.from(new Uint8Array(hashBuffer));<br>  // You will have to implement `toBase64` yourself or use some library<br>  return toBase64(hashArray).slice(0, 6);<br>}</pre><h3>Translate the site into any number of languages with a single command</h3><p>I would never have been able to sell the idea of migrating from i18next to LinguiJS if I didn&#39;t have a plan for how we would translate our application into other languages more or less automatically.</p><p>At first, I thought we would use something like <a href="https://crowdin.com/">CrowdIn</a>. In the LinguiJS documentation, there is a <a href="https://lingui.dev/tools/crowdin">section on integration</a>.</p><p>That’s how it would have been if, among dozens of translation services, a real game-changer hadn’t appeared — <a href="https://translation.io/lingui">translation.io</a></p><p>As sponsors of LinguiJS, translation.io offers a zero-install solution for translations to anyone using LinguiJS.</p><p>The familiar lingui extract command will send your PO files for translation and download them back.</p><p>After creating a project on translation.io, you will be prompted to add an API key to the .linguirc config:</p><pre>// .linguirc<br>{<br>  &quot;service&quot;: {<br>    &quot;name&quot;: &quot;TranslationIO&quot;,<br>    &quot;apiKey&quot;: &quot;tyq00pq1uw3xnmrtpjbpzlwh9k&quot;<br>  },<br>  &quot;sourceLocale&quot;: &quot;en&quot;,<br>  &quot;locales&quot;: [<br>    &quot;en&quot;,<br>    &quot;ka&quot;<br>  ],<br>}</pre><blockquote><em>Keep an eye on how many languages you are translating the interface into — it’s not free. Although translation.io has one of the most flexible pricing policies (young startups will appreciate it), don’t forget to monitor expenses in the control panel.</em></blockquote><p>All that’s left is to send the untranslated PO files to the service. We run lingui extract:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SoDvIjxguxArjWEExfzRxA.png" /><figcaption>lingui extract Console output</figcaption></figure><p>We noticed that we don’t have a translation into Georgian yet. A link to the project will be offered in the console. In my case, it’s <a href="https://translation.io/radist2s/artm-store.">https://translation.io/radist2s/artm-store.</a></p><p>We go there, but don’t waste time — straight to the list of projects, and then <em>Settings</em>.</p><p>The coveted <em>Auto-Translation</em> section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqiYrA_OVT6uNQmAEZLCwQ.png" /><figcaption>translation.io interface</figcaption></figure><p>Here you can specify the languages you want to translate your application into automatically. Use Google Translate, DeepL, or OpenAI if you want. Click <em>Translate now</em>, wait a minute, and repeat the lingui extract command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bciKSEdO5-wFr5vfN_zupw.png" /><figcaption>We ignore the 1 missing translation, these are the subtleties of my internal implementation</figcaption></figure><p>And that’s it! Now, when you add new messages to the site, they will be automatically translated into the target language(s) every time you run lingui extract. Isn’t that cool?</p><h3>Conclusions</h3><h4>Don’t be afraid of major refactoring</h4><p>jscodeshift is not a silver bullet. On the contrary, writing a working transformer can take a lot of time. But you don&#39;t have to cover all cases, just identify the most popular constructs and write a transformer for them.</p><h4>Write your own linting rules</h4><p>Whether you’re using a new approach that you’d like to establish within the team, or introducing a strange template syntax — write your own linting rules.</p><p>It’s not just a means of preventing errors, but also another way to share new knowledge with the team.</p><h4>Carefully study the compilation result</h4><p>From time to time, explore your /dist directory. In our case, it would have been wise to study what results from the compilation of the t macro in advance, so as not to waste time on additional refactoring.</p><h3>Links</h3><ul><li><a href="https://lingui.js.org/">LinguiJS</a></li><li><a href="https://github.com/radist2s/i18next-to-linguijs-jscodeshift-transformer">i18next to LinguiJS jscodeshift Transformer</a></li><li><a href="https://github.com/igorDolzh/eslint-plugin-lingui">ESLint Rules for LinguiJS</a></li><li><a href="https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html">The Format of PO Files</a></li><li><a href="https://cldr.unicode.org/index/cldr-spec/plural-rules">ICU MessageFormat Plural Rules</a></li><li><a href="https://codemod.studio/">Codemod Studi</a>o✨ — brand-new IDE for writing jscodeshift transformers using three different LLMs</li></ul><h4>Thanks</h4><p>Special thanks to LinguiJS Team for their work and especially to <a href="https://github.com/thekip">Tim Iatsenko</a> for the assistance in writing the article and its review.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b07ac73a9bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>