perf(i18n): lazy-load locale catalogs instead of bundling every language (#2362)

Co-authored-by: Kandev Agent <agent@kandev.dev>
This commit is contained in:
João Salavisa
2026-08-07 19:43:42 +02:00
committed by GitHub
parent 224206e6d8
commit d855d615f8
10 changed files with 675 additions and 44 deletions
+65 -2
View File
@@ -220,6 +220,16 @@ which `vite.config.ts` defines from `shouldBundlePseudoLocale` in
modules into the graph. Filtering the merged catalog at runtime instead would
still ship every byte, which is the entire problem.
**Lazy loading is not a substitute for this, and the two compose rather than
overlap.** Catalogs are fetched on demand (see
[Catalog loading](#catalog-loading-and-why-en-is-the-exception)), so pseudo would
be a chunk nobody requests in production — but an unrequested chunk is still
built, still deployed, and still reachable by anyone who can set the
`kandev_locale` cookie. The build-time constant is folded into the *lazy* glob
for exactly that reason: on a plain `vite build` no pseudo chunk is emitted at
all. Nothing asserts on that absence, so check it by hand when either mechanism
changes — `grep -rl "Ŕēţŕŷ" dist/assets/*.js` must return nothing.
| invocation | pseudo? |
| ----------------------------------------------------------------------- | ------- |
| `pnpm dev`, `vitest` (Vite `serve`) | yes |
@@ -468,11 +478,64 @@ the completeness check.
`<I18nProvider>` (mounted outermost in `app-shell.tsx`), `resolveInitialLocale`
(payload → cookie → `en`), and `formats.ts` (locale-aware date/number/relative
time; `timeAgo` is a deprecated alias for `formatRelative`).
- **Catalogs**: `src/locales/<locale>/<namespace>.json`, loaded eagerly through
Vite's glob import — no build plugin and no macro transform.
- **Catalogs**: `src/locales/<locale>/<namespace>.json`, discovered through
Vite's glob import — no macro transform. **`en` is bundled eagerly; every
other locale is a lazily-fetched chunk** (see below). The one build plugin is
`kandev:i18n-pseudo-locale-bundling` in `vite.config.ts`, which decides
whether the `pseudo` catalog is compiled in at all.
- **Locale source of truth**: the `kandev_locale` cookie. The Go shell
(`apps/backend/internal/webapp/shell.go`) reads it to set `<html lang>` and
seed the boot payload, so first paint matches with no flash.
### Catalog loading, and why `en` is the exception
Bundling every locale put all of them in the initial download — 1.4 MB raw /
389 KB gzipped, growing linearly with each locale added, so that a user could
read one language they had downloaded four of. Only `en` is eager now; the rest
are fetched per locale.
Two things make that safe rather than a source of flashing keys:
- **`en` must be synchronous.** It is `DEFAULT_LOCALE` and `fallbackLng`, and
`returnNull: false` means a missing key renders as _the key itself_. If `en`
were not in memory when `i18next.init()` returns, every key on screen would
paint as `common:save` until a chunk landed — silent and ugly rather than
loud. Keeping it eager also keeps `ensureInitialized` synchronous, which the
boot path depends on: react-i18next suspends on an uninitialized instance and
there is no Suspense boundary above the React root.
- **The active locale is known before React mounts.** The Go shell resolves it
into the boot payload, so `main.tsx` awaits exactly ONE locale
(`preloadLocale`) inside the promise it already waited on for the payload,
_before_ `createRoot().render()`. Nothing renders against a half-loaded
catalog. For `en` that await resolves immediately and the boot is unchanged.
A runtime switch goes through `activateLocale`, which loads **before**
`changeLanguage` rather than on the `languageChanged` event — `changeLanguage`
re-renders the whole tree, so registering afterwards would show one frame of
English. A failed chunk never throws: the app degrades to English under the
requested `<html lang>`, and `installVitePreloadRecovery` reloads once on
`vite:preloadError`.
`vite.config.ts` groups each locale's namespaces into a single chunk. i18next is
seeded with every namespace and any surface may use any of them, so a locale is
always loaded whole; a chunk per namespace would cost a non-English boot 29 round
trips for the same bytes.
Unit tests are the one place that still wants everything in memory — suites call
`i18n.changeLanguage("pseudo")` and assert on the next line — so
`vitest.setup.ts` awaits `loadAllLocalesForTests()` once.
`pseudo-coverage.spec.ts` already tolerates this, and it is worth knowing why it
does not need a change here. Its `waitForScreen` anchors assert per screen that
the route rendered **and** that the anchor's copy went accented — the second half
was written as insurance against exactly this, a catalog arriving asynchronously,
back when it was still hypothetical. `<html lang>` alone would not have done:
`shell.go` writes it server-side, so it is correct before any script runs.
`e2e/tests/i18n/lazy-catalogs.spec.ts` is the gate. It asserts against a real
production bundle that an English boot fetches no other catalog, that activating
one fetches exactly its chunk, and that a cold `zh-cn` boot renders translated
rather than key names.
- **Shared UI**: `@kandev/ui` primitives carry their own hardcoded accessibility
labels ("Close", "Toggle Sidebar", "Loading", "Go to next page"). The package
must not import the app's i18n runtime — it has to stay usable standalone — so
+9 -1
View File
@@ -102,7 +102,11 @@ i18n adds no server-side persistent entities. It introduces:
rather than failing, and i18next falls back to `en` at runtime; `pseudo` is
generated from `en` by
`scripts/generate-pseudo-locale.mjs` and is never hand-edited. Catalogs load at
runtime via Vite glob import — no build plugin.
runtime via Vite glob import — no build plugin. Only `en` is bundled into the
initial download: it is the fallback locale, so it has to be in memory the
moment i18next initializes or every key paints as its own name. Every other
locale is one lazily-fetched chunk, and the boot awaits exactly the active
one — resolved by the Go shell into the boot payload — before React mounts.
- **Locale preference** — the user's chosen locale, one value from the supported
set. A dedicated `kandev_locale` cookie is the authoritative persisted value
read by the Go shell so the initial `<html lang>` and first paint match the
@@ -190,6 +194,10 @@ Frontend module contract (new):
`DEFAULT_LOCALE` (`en`) and does not throw.
- **Malformed catalog JSON** → the Vite glob import fails the build (caught in
CI), never shipped.
- **A locale's catalog chunk fails to fetch** → the app renders in `en` under the
requested `<html lang>`; it never blanks, throws, or blocks the boot. `en` is
bundled, so the fallback is always available. `installVitePreloadRecovery`
reloads once on `vite:preloadError`, and the next boot retries.
- **`@kandev/ui` used without an injected dictionary** → primitives use their
English `defaultProps`; no runtime dependency on the app i18n instance.