New Sep 18, 2024

Creating a React library with Vite and Lingui

Libraries, Frameworks, etc. All from Newest questions tagged reactjs - Stack Overflow View Creating a React library with Vite and Lingui on stackoverflow.com

I'm trying to create a React library with Lingui using Vite.

For simplicity let's say I have a Welcome component:

import { Trans } from "@lingui/macro";

function Welcome() { return ( <div> <Trans context="Library">Library welcome</Trans> </div> ); }

export default Welcome;

The library also provides an I18nApp:

function I18nApp({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    dynamicActivate("en");
  }, []);

return <I18nProvider i18n={i18n}>{children}</I18nProvider>; }

And dynamicActivate:

import { i18n } from "@lingui/core";

async function dynamicActivate(locale: string) { //somehow either as strings or loaded files it will get the app's .po files, but its currently empty const mergedPaths: string[] = [];

const { message: libraryTranslation } = await import(./assets/locales/${locale}.po); let mergedMessages = libraryTranslation || {};

for (const translationPath of mergedPaths) { const { messages } = await import(${translationPath}/locales/${locale}.po); mergedMessages = { ...mergedMessages, ...messages }; }

i18n.load(locale, mergedMessages); i18n.activate(locale); }

export default dynamicActivate;

And I have an app welcome as well:

import { Trans } from "@lingui/macro";

function Welcome() { return ( <div> <Trans context="App">App welcome</Trans> </div> ); }

export default Welcome;

How can I bundle the library with it's corresponding .po translation files (the files are in src/assets/locales)? I believe if I can do that, I can provide the app's .po files in one way or the other to dynamicActivate and that should be rather straight forward. What setting should I turn on in lingui.config.ts or vite.config.ts? Or what documentation can I follow?

Scroll to top