SayKit
Guides

Dynamic loading

Load locale catalogues lazily to keep bundles small

Each locale in a catalogue is either:

  • Inline: the imported messages. Bundled, and ready synchronously.
  • A thunk: a function producing them, usually a dynamic import(). Its own chunk, loaded the first time it is needed.

Inline suits a few locales, servers and CLIs. Thunks suit many locales and browser apps, at the cost of an async switch. Most apps mix the two.

Inline

src/i18n.ts
import { createCatalogue } from 'saykit';
import en from './locales/en.js';
import fr from './locales/fr.js';

export const catalogue = createCatalogue({ en, fr });

catalogue.locale('fr') is synchronous, with no loading state.

Thunks

src/i18n.ts
export const catalogue = createCatalogue({
  en: () => import('./locales/en.js'),
  fr: () => import('./locales/fr.js'),
  ja: () => import('./locales/ja.js'),
});

const say = await catalogue.load('fr');

The catalogue reads the messages off the module's default export, so there is nothing to unwrap. One thunk per locale, rather than one function taking a locale, keeps every import a literal the bundler can see, so the shipped locales are decided at build time. The modules are ordinary .js, so this works the same under every plugin.

Hybrid

Inline the source locale and lazy-load the rest, so the first render is synchronous:

src/i18n.ts
import en from './locales/en.js';

export const catalogue = createCatalogue({
  en,
  fr: () => import('./locales/fr.js'),
  ja: () => import('./locales/ja.js'),
});

In a browser, a store loads and switches in one step with store.set(locale). If the starting locale is lazy, load it before creating the store:

const initial = catalogue.match(navigator.languages);
await catalogue.load(initial);
export const store = createStore(catalogue, initial);

Preloading on hover

<a href={`/${locale}`} onMouseEnter={() => catalogue.load(locale)}>
  {locale}
</a>

load() is safe to call repeatedly: a loaded locale returns synchronously, overlapping loads share one call, and only a failed thunk is called again.

Server-side

Load the locale each request needs. The catalogue and its views are safe to share between requests:

export function sayFor(locale: string) {
  return catalogue.load(catalogue.match(locale));
}

To pay every import once at boot instead:

await Promise.all(catalogue.locales.map((locale) => catalogue.load(locale)));

A thunk can also return the messages synchronously, in which case load() returns the view rather than a promise.

Next

On this page