Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strip unneeded locales and translations #186

Open
Myphz opened this issue Jul 15, 2024 · 0 comments
Open

Strip unneeded locales and translations #186

Myphz opened this issue Jul 15, 2024 · 0 comments

Comments

@Myphz
Copy link

Myphz commented Jul 15, 2024

Hello! I've been using this library for a couple of months with SSR. I have followed the locale-router example.

In that example, the layout.server.ts is in charge of loading the needed translations and sending them to the other pages (namely, layout.ts/layout.js). After loading the translations, layout.server.ts returns translations: translations.get(). As noted in the locale-param examples, the translations variable on server contain all translations loaded by different clients.

This means that, after loading the needed translations based on route and locale, the server then sends ALL loaded translations to the client, not just the needed ones. This can easily be verified on the HTML output: all translations that the server has loaded so far are sent, including unneeded languages and unneeded keys from other routes.

I haven't found an option in the library to automatically strip unneeded translations, so I have developed my own utility function in layout.server.ts:

// Remove unneeded translation keys and languages
const getStrippedTranslations = (lang: string, route: string) => {
  const keysToLoad = [
    ...new Set(
      config.loaders
        .filter(
          (loader) => !loader.routes?.length || loader.routes.some((r) => new RegExp(r).test(route))
        )
        .map((loader) => loader.key)
    )
  ];

  return {
    [lang]: Object.fromEntries(
      Object.entries(translations.get()[lang]).filter(([key]) => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        if (AVAILABLE_LANGUAGES.includes(key as any)) return true;
        if (keysToLoad.some((keyToLoad) => key.startsWith(keyToLoad))) return true;
        return false;
      })
    )
  };
};

export const load: LayoutServerLoad = async ({ url, locals }) => {
  const { pathname } = url;
  const { lang } = locals;

  await loadTranslations(lang, pathname);

  return { i18n: { route: pathname, lang }, translations: getStrippedTranslations(lang, pathname) };
};

I believe this optimization should be handled automatically by the library, as the payload can become quite large for websites with a lot of content.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant