### Installing compiled-i18n as a Dev Dependency
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
These commands show how to install `compiled-i18n` as a development dependency using popular package managers: npm, pnpm, and yarn. This is the first step to integrate the library into a project.
```sh
npm install --save-dev compiled-i18n
pnpm i -D compiled-i18n
yarn add -D compiled-i18n
```
--------------------------------
### TypeScript Helper for compiled-i18n Locale Setup
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/astro-qwik.md
This TypeScript file (`src/lib/i18n-setup.ts`) provides functions to manage `compiled-i18n`'s locale settings across server and client environments. It includes `setupI18nServer` to determine the locale during SSR, `setupI18nClient` for client-side locale adjustments (especially in development), and `setCurrentLocale` to set the global current locale.
```TypeScript
// src/lib/i18n-setup.ts
import {
setLocaleGetter,
setDefaultLocale,
locales as compiledLocales, // Locales known by compiled-i18n
} from 'compiled-i18n'
// Assuming DEFAULT_LOCALE is your app's default locale string (e.g., 'en')
// imported from your Astro i18n configuration (e.g., '@/i18n')
import {DEFAULT_LOCALE} from '@/i18n'
export function setupI18nServer() {
setLocaleGetter(() => {
let currentSsrLocale: string | undefined
if (
typeof globalThis !== 'undefined' &&
(globalThis as any).currentLocale
) {
currentSsrLocale = (globalThis as any).currentLocale
}
if (currentSsrLocale && compiledLocales.includes(currentSsrLocale)) {
return currentSsrLocale
}
if (compiledLocales.includes(DEFAULT_LOCALE)) {
return DEFAULT_LOCALE
}
return compiledLocales[0] || 'en' // Fallback to the first known or 'en'
})
}
export function setupI18nClient() {
if (import.meta.env.DEV) {
const htmlLang = document.documentElement.lang
let targetLocale = DEFAULT_LOCALE
if (htmlLang) {
if (compiledLocales.includes(htmlLang)) {
targetLocale = htmlLang
} else {
const baseLang = htmlLang.split('-')[0]
if (compiledLocales.includes(baseLang)) {
targetLocale = baseLang
}
}
}
if (!compiledLocales.includes(targetLocale)) {
targetLocale = compiledLocales.includes(DEFAULT_LOCALE)
? DEFAULT_LOCALE
: compiledLocales[0] || 'en'
}
setDefaultLocale(targetLocale)
}
// In production, locale is fixed per-bundle, setDefaultLocale has no effect.
}
export function setCurrentLocale(locale: string) {
if (typeof globalThis !== 'undefined') {
;(globalThis as any).currentLocale = locale
}
}
```
--------------------------------
### Qwik Client-Side Route-Based Locale Redirection (index.tsx)
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/qwik.md
This `onGet` handler, located in `/src/routes/index.tsx`, is responsible for redirecting initial GET requests to a locale-prefixed URL. It guesses the user's preferred locale from the `accept-language` header and then performs a 301 redirect to include this guessed locale in the URL path.
```tsx
import type {RequestHandler} from '@builder.io/qwik-city'
import {guessLocale} from 'compiled-i18n'
export const onGet: RequestHandler = async ({request, redirect, url}) => {
const acceptLang = request.headers.get('accept-language')
const guessedLocale = guessLocale(acceptLang)
throw redirect(301, `/${guessedLocale}/${url.search}`)
}
```
--------------------------------
### Astro Configuration for compiled-i18n Integration
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/astro-qwik.md
This snippet shows the `astro.config.mjs` setup required to integrate `compiled-i18n` with Astro. It demonstrates how to define Astro's i18n settings and include the `@qwikdev/astro` integration along with `i18nPlugin` from `compiled-i18n/vite`, ensuring locale consistency between Astro and the i18n plugin.
```JavaScript
// astro.config.mjs
import {defineConfig} from 'astro/config'
import qwikdev from '@qwikdev/astro'
import {i18nPlugin} from 'compiled-i18n/vite'
// Assuming you have locale definitions, e.g., from './src/locales.ts'
import {DEFAULT_LOCALE_SETTING, LOCALES_SETTING} from './src/locales'
export default defineConfig({
site: 'https://example.com', // Your site URL
i18n: {
defaultLocale: DEFAULT_LOCALE_SETTING, // e.g., "en"
locales: Object.keys(LOCALES_SETTING), // e.g., ["en", "fr", "es"]
routing: {
prefixDefaultLocale: true, // Or your preferred routing strategy
},
},
integrations: [
qwikdev(),
// ... other integrations
],
vite: {
plugins: [
i18nPlugin({
locales: Object.keys(LOCALES_SETTING), // Must match Astro's locales
defaultLocale: DEFAULT_LOCALE_SETTING,
localesDir: './src/i18n', // Directory for your .json translation files
addMissing: true,
// assetsDir is typically 'build/' by default when qwikVite plugin is detected
}),
// ... other Vite plugins
],
},
})
```
--------------------------------
### Create Qwik Locale Selector Component
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/qwik.md
This example provides a client-side Qwik component for users to change the locale. It iterates through available locales, highlights the current one, and generates links that reload the page with the selected locale via a query parameter. It emphasizes using `` tags instead of `` for necessary page reloads.
```tsx
import {component$, getLocale} from '@builder.io/qwik'
import {_, locales} from 'compiled-i18n'
export const LocaleSelector = component$(() => {
const currentLocale = getLocale()
return (
<>
{locales.map(locale => {
const isCurrent = locale === currentLocale
return (
// Note, you must use `` and not `` so the page reloads
{locale}
)
})}
>
)
})
```
--------------------------------
### Define Translation Files for compiled-i18n
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/astro-qwik.md
This section explains the structure of JSON translation files required by `compiled-i18n`. It provides examples for English and French, demonstrating how to define locale-specific information and translation keys with their corresponding values, including placeholders for interpolation.
```json
{
"locale": "en",
"name": "English",
"translations": {
"welcomeMessage": "Welcome!",
"greeting $1": "Hello, $1!"
}
}
```
```json
{
"locale": "fr",
"name": "Français",
"translations": {
"welcomeMessage": "Bienvenue !",
"greeting $1": "Bonjour, $1 !"
}
}
```
--------------------------------
### Use compiled-i18n in Qwik Components
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/astro-qwik.md
This snippet illustrates how to use the `_` tag from `compiled-i18n` within a Qwik component to display translated messages. It shows examples of simple key-based translation and translation with interpolated variables, where placeholders like `$1` are replaced by dynamic values.
```tsx
// src/components/MyQwikComponent.tsx
import {component$, useSignal} from '@builder.io/qwik'
import {_} from 'compiled-i18n'
export default component$(() => {
const userName = useSignal('Qwik')
return (
{_`welcomeMessage`}
{' '}
{/* Key "welcomeMessage" must exist in your .json files */}
{_`greeting ${userName.value}`}
{/* Key "greeting $1" */}
)
})
```
--------------------------------
### Utility API Function: makeKey
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
Calculates and returns the unique key for a given array of template strings. For example, it converts `["Hi ", ""]` into the key `"Hi $1"`.
```APIDOC
`makeKey(...tpl: string[]): string`
Description: Returns the calculated key for a given template string array. For example, it returns `"Hi $1"` for `["Hi ", ""]`
```
--------------------------------
### API: `locales` Property
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This API documentation describes the `locales` property, which is a read-only array containing all configured locales. For example, it might contain `['en_US', 'fr']`.
```APIDOC
locales: readonly string[]
Description: The locales you configured, for example `['en_US', 'fr']`.
```
--------------------------------
### Example of a Plural Translation Object in JSON
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This JSON snippet demonstrates a Plural object used for handling different forms of a translation based on an interpolated value. It shows how specific numbers or string keys can map to direct translations or reference other keys, with a wildcard '*' for a default fallback.
```json
{
"$1 items": {
"0": "no items",
"1": "some items",
"2": 1,
"3": "three items",
"three": 3,
"*": "many items ($1)"
}
}
```
--------------------------------
### Setting Server-Side Locale Getter for compiled-i18n
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This TypeScript snippet demonstrates how to configure the server-side locale getter using `setLocaleGetter` from `compiled-i18n`. It shows an example integration with Qwik's `getLocale` function to dynamically determine the current locale for translations.
```ts
import {defaultLocale, setLocaleGetter} from 'compiled-i18n'
import {getLocale} from '@builder.io/qwik'
setLocaleGetter(() => getLocale(defaultLocale))
```
--------------------------------
### Example of Nested Plural Translation Object in JSON
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This JSON snippet illustrates how Plural objects can be nested to handle multiple interpolation parameters sequentially. The first parameter selects the top-level key, and subsequent parameters select keys within the nested objects, allowing for complex conditional translations.
```json
{
"time:$1.$2.$3": {
"short": "$3$2",
"long": {
"AM": "It is $3 in the morning",
"PM": "It is $3 in the afternoon"
}
}
}
```
--------------------------------
### Qwik Server-Side Rendering (SSR) Configuration for compiled-i18n
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/qwik.md
This code snippet illustrates how to configure the server entry point (`entry.ssr.tsx`) in a Qwik application for `compiled-i18n` integration. It involves importing necessary helpers, enabling SSR locale retrieval, setting the asset base path, and dynamically configuring the HTML `lang` attribute based on the detected SSR locale.
```tsx
// +++ Extra import
import {extractBase, setSsrLocaleGetter} from 'compiled-i18n/qwik'
// +++ Allow compiled-i18n to get the current SSR locale
setSsrLocaleGetter()
export default function (opts: RenderToStreamOptions) {
return renderToStream(, {
manifest,
...opts,
// +++ Configure the base path for assets
base: extractBase,
// Use container attributes to set attributes on the html tag.
containerAttributes: {
// +++ Set the HTML lang attribute to the SSR locale
lang: opts.serverData!.locale,
...opts.containerAttributes,
},
})
}
```
--------------------------------
### Configure compiled-i18n in Astro Base Layout
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/astro-qwik.md
This snippet demonstrates how to set up `compiled-i18n` within an Astro base layout. It shows server-side rendering (SSR) configuration using `setupI18nServer` and `setCurrentLocale` to pass the current Astro locale, and client-side initialization with `setupI18nClient` for development mode, ensuring the correct locale is available for Qwik components.
```astro
---
// src/layouts/Base.astro
import { setupI18nServer, setCurrentLocale } from "@/lib/i18n-setup";
import { LOCALES, DEFAULT_LOCALE, type Lang } from "@/i18n"; // Your Astro i18n helpers
const currentAstroLocale = Astro.currentLocale as Lang;
// For SSR: Set up compiled-i18n before Qwik components render
if (import.meta.env.SSR) {
setupI18nServer(); // Configures the locale getter for compiled-i18n
setCurrentLocale(currentAstroLocale); // Makes the current locale available to the getter
}
const localeObject = LOCALES[currentAstroLocale] || LOCALES[DEFAULT_LOCALE as Lang];
---
{/* ... other head elements ... */}
{/* ... header, main content slot ... */}
{/* Qwik components will be rendered within this slot */}
{/* ... footer ... */}
{/* For client-side development mode: initialize compiled-i18n */}
```
--------------------------------
### Configure compiled-i18n Vite Plugin Order for Older Qwik
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/qwik.md
This snippet provides the Vite configuration for Qwik applications using versions lower than 1.8. It demonstrates how to correctly place `i18nPlugin` at the top of the plugin list to ensure proper functionality.
```ts
import {qwikVite} from '@builder.io/qwik/optimizer'
import {qwikCity} from '@builder.io/qwik-city/vite'
import {defineConfig} from 'vite'
import {i18nPlugin} from 'compiled-i18n/vite'
export default defineConfig({
plugins: [
i18nPlugin({
locales: ['en_us', 'en_uk', 'en', 'nl'],
}),
qwikCity(),
qwikVite(),
],
})
```
--------------------------------
### Qwik compiled-i18n: extractBase API Reference
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/qwik.md
This helper function is designed to set the base path for assets within a Qwik application. It should be passed to the `base` property of the render options. In development mode, the base path defaults to `/build`, while in production it becomes `/build/${locale}`, also incorporating any base path provided to Vite.
```APIDOC
extractBase({serverData}: RenderOptions): string
serverData: RenderOptions object containing server-side data.
Returns: string - The calculated base path for assets.
```
--------------------------------
### Qwik Client-Side Query-Based Locale Handling (layout.tsx)
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/qwik.md
This `onRequest` handler, located in `/src/routes/layout.tsx`, is responsible for setting the locale based on a query parameter or the `accept-language` header. It allows developers to override the locale using the `locale` query parameter and gracefully falls back to guessing the locale from the `accept-language` header if the parameter is not provided.
```tsx
// ... other imports
import {guessLocale} from 'compiled-i18n'
export const onRequest: RequestHandler = async ({query, headers, locale}) => {
// Allow overriding locale with query param `locale`
const maybeLocale = query.get('locale') || headers.get('accept-language')
locale(guessLocale(maybeLocale))
}
```
--------------------------------
### API: Runtime Translation with `localize` or `_`
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This API documentation details the runtime translation function, `localize` (or `_`), which uses in-memory maps for translation. It clarifies that keys are not altered at build time, meaning interpolated template strings generate unique keys rather than using `$n` placeholders. Users are responsible for loading translation data via `loadTranslations`.
```APIDOC
localize(key: I18nKey, ...params: any[]) or _(key: I18nKey, ...params: any[]): Runtime translation
Description: Translates the given string at runtime, using in-memory maps that you need to provide.
The key is not changed at build time, interpolations of template strings are not converted to `$`+number.
This means that when you do interpolate, you are generating new keys instead of a single key with a `$1` placeholder.
It is also your duty to call `loadTranslations` with data you provide, so the requested translations are present.
The built client code will not include any translations.
Missing translations use the key.
Example:
const name = 'Wout'
_`Hi ${name}!` // key: "Hi $1", params: ["Wout"]
_(`Hi ${name}`) // key: "Hi Wout", params: []
```
--------------------------------
### Vite API Plugin: i18nPlugin with Options
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
The Vite plugin for `compiled-i18n` integrates internationalization into the build process. It accepts an `Options` object to configure various aspects like supported locales, directory paths, default locale, Babel plugins, asset output directory, and automatic key management.
```APIDOC
`i18nPlugin(options?: Options)`
Description: The vite plugin accepts these options.
```
```TypeScript
type Options = {
/** The locales you want to support */
locales?: string[]
/** The directory where the locale files are stored, defaults to /i18n */
localesDir?: string
/** The default locale, defaults to the first locale */
defaultLocale?: string
/** Extra Babel plugins to use when transforming the code */
babelPlugins?: any[]
/**
* The subdirectory of browser assets in the output. Locale post-processing
* and locale subdirectory creation will only happen under this subdirectory.
* Do not include a leading slash.
*
* If the qwikVite plugin is detected, this defaults to `build/`.
*/
assetsDir?: string
/** Automatically add missing keys to the locale files. Defaults to true */
addMissing?: boolean
/** Automatically remove unused keys from the locale files. Defaults to false. */
removeUnusedKeys?: boolean
/** Use tabs on new JSON files */
tabs?: boolean
}
```
--------------------------------
### Configuring compiled-i18n Vite Plugin
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This TypeScript snippet demonstrates how to integrate the `compiled-i18n` Vite plugin into a `vite.config.ts` file. It shows how to import `i18nPlugin` and add it to the `plugins` array, specifying the locales to be processed.
```ts
import {defineConfig} from 'vite'
import {i18nPlugin} from 'compiled-i18n/vite'
export default defineConfig({
plugins: [
// ... other plugins
i18nPlugin({
locales: ['en_us', 'en_uk', 'en', 'nl'],
}),
],
})
```
--------------------------------
### Qwik Client-Side Route-Based Locale Handling (layout.tsx)
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/qwik.md
This `onRequest` handler, found in `/src/routes/[locale]/layout.tsx`, manages locale setting and redirection for route-based locale selection. It validates the `locale` parameter from the URL, sets the Qwik locale for the current request, or redirects to a valid locale if the current one is invalid or missing, using the `accept-language` header for locale guessing.
```tsx
import {component$, Slot} from '@builder.io/qwik'
import type {RequestHandler} from '@builder.io/qwik-city'
import {guessLocale, locales} from 'compiled-i18n'
const replaceLocale = (pathname: string, oldLocale: string, locale: string) => {
const idx = pathname.indexOf(oldLocale)
return (
pathname.slice(0, idx) + locale + pathname.slice(idx + oldLocale.length)
)
}
export const onRequest: RequestHandler = async ({
request,
url,
redirect,
pathname,
params,
locale,
}) => {
if (locales.includes(params.locale)) {
// Set the locale for this request
locale(params.locale)
} else {
const acceptLang = request.headers.get('accept-language')
// Redirect to the correct locale
const guessedLocale = guessLocale(acceptLang)
const path =
// You can use `__` as the locale in URLs to auto-select it
params.locale === '__' ||
/^([a-z]{2})([_-]([a-z]{2}))?$/i.test(params.locale)
? // invalid locale
'/' + replaceLocale(pathname, params.locale, guessedLocale)
: // no locale
`/${guessedLocale}${pathname}`
throw redirect(301, `${path}${url.search}`)
}
}
export default component$(() => {
return
})
```
--------------------------------
### API: Compile-time Translation with `localize` or `_`
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This API documentation describes the compile-time translation function, `localize` (or `_`), which processes template literal strings. It explains how interpolations are converted to `$n` placeholders for lookup keys and how literal `$` characters are escaped. It also shows how nesting translations can be achieved by passing translated strings back into the function.
```APIDOC
localize`str` or _`str`: Compile-time translation
Description: Translates the given string at compile time.
Interpolations are converted to `$`+number to make a lookup key, and then the key is looked up in the JSON file.
A literal `$` will be converted to `$$`.
Missing translations fall back to the key.
Nesting is achieved by passing result strings into translations again.
Example:
_`Hi ${honorific}${name}!` converts into a lookup of the I18nKey "Hi $1 $2".
_`There are ${_`${boys} boys`} and ${_`${girls} girls`}.`
```
--------------------------------
### Clean URL Query Parameters in Qwik useOnDocument
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/qwik.md
This code snippet shows how to remove unwanted query parameters from the URL after the page loads. It uses `useOnDocument` to listen for the 'load' event and `history.replaceState` to update the URL, keeping only specified allowed parameters.
```tsx
useOnDocument(
'load',
$(() => {
// remove all query params except allowed
const allowed = new Set(['page'])
if (location.search) {
const params = new URLSearchParams(location.search)
for (const [key] of params) {
if (!allowed.has(key)) {
params.delete(key)
}
}
let search = params.toString()
if (search) search = '?' + search
history.replaceState(
history.state,
'',
location.href.slice(0, location.href.indexOf('?')) + search
)
}
})
)
```
--------------------------------
### Utility API Function: guessLocale
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
Parses an `Accept-Language` header string and returns the first matching locale configured in the application. If the input string is invalid, it returns `undefined`. If no match is found, it falls back to the `defaultLocale`.
```APIDOC
`guessLocale(acceptsLanguage: string)`
Description: Given an `accepts-language` header value, return the first matching locale.
Returns: `undefined` if the given string is invalid. Falls back to `defaultLocale`.
```
--------------------------------
### Using _ or localize Function for String Translation
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This TypeScript/JSX snippet illustrates the basic usage of the `_` function (or `localize`) from `compiled-i18n` to mark strings for translation. It emphasizes the use of template string notation and shows how variables can be interpolated into translatable strings.
```tsx
import {_} from 'compiled-i18n'
// ...
const name = 'John'
const emoji = '👋'
const greeting = _`Hello ${name} ${emoji}!`
```
--------------------------------
### Localizing Strings with compiled-i18n in JSX
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This snippet demonstrates how to use the `_` function from `compiled-i18n` to mark strings for translation within JSX components and console logs. It shows basic template string interpolation for dynamic values.
```jsx
import {_} from 'compiled-i18n'
console.log(_`Logenv ${process.env.NODE_ENV}`)
export const Count = ({count}) => (
{_`${count} items`}
)
```
--------------------------------
### French Translation JSON File Structure
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This JSON snippet illustrates the structure of a translation file for the French locale. It includes locale metadata, fallback settings, and a `translations` object mapping original keys to their translated values, including nested objects for pluralization.
```json
{
"locale": "fr",
"fallback": "en",
"name": "Français",
"translations": {
"Logenv $1": "Mode de Node.JS: $1",
"countTitle": "Nombre d'articles",
"$1 items": {
"0": "aucun article",
"1": "un article",
"*": "$1 articles"
}
}
}
```
--------------------------------
### API Property: localeNames
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
Provides a read-only constant map of configured locale names, mapping locale keys to their human-readable names. This property reflects the locale names defined during the library's configuration.
```APIDOC
`localeNames: readonly const {[key: string]: string}`
Description: The locale names you configured, for example `{en_US: "English (US)", fr: "Français"}`.
```
--------------------------------
### Utility API Function: interpolate
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
Performs parameter interpolation on a given translation string or plural object, replacing placeholders with provided parameters. This function is generally for internal use and not typically called directly by applications.
```APIDOC
`interpolate(translation: I18nTranslation | I18nPlural, ...params: unknown[])`
Description: Perform parameter interpolation given a translation string or plural object. Normally you won't use this.
```
--------------------------------
### API Function: loadTranslations
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
Adds new translations for a specific locale to the in-memory translation map. If no locale is provided, it defaults to the `currentLocale`. This function is essential for dynamic translation loading and must be called on both client and server (for SSR) to ensure consistent translation availability.
```APIDOC
`loadTranslations(translations: I18n.Data['translations'], locale?: string)`
Description: Add translations for a locale to the in-memory map. If you don't specify the locale, it uses `currentLocale`.
Usage: Only needed for dynamic translations. Must be run on both client and server (when using SSR).
```
--------------------------------
### Translated JSX Output (French)
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This snippet shows the resulting French translated code after `compiled-i18n` processes the original JSX. It illustrates how template strings are replaced with direct translations and how pluralization is handled using an `interpolate` function.
```jsx
import {interpolate} from 'compiled-i18n'
console.log(`Mode de Node.JS: ${process.env.NODE_ENV}`)
export const Count = ({count}) => (
)
```
--------------------------------
### Qwik compiled-i18n: setSsrLocaleGetter API Reference
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/qwik.md
This function configures `compiled-i18n` to retrieve the current locale from Qwik during Server-Side Rendering (SSR). It is crucial to call this function in your `entry.ssr` file to ensure proper locale detection on the server.
```APIDOC
setSsrLocaleGetter(): void
Returns: void
```
--------------------------------
### Utility API Property: defaultLocale
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
Represents the default locale used by the library, which is initially set to the first configured locale. This value can be overridden at runtime using `setDefaultLocale`, primarily for development purposes on the client side.
```APIDOC
`defaultLocale: readonly string`
Description: Default locale, defaults to the first specified locale. Can be set with `setDefaultLocale`, useful during dev mode on the client side if you can't change the HTML's `lang` attribute.
```
--------------------------------
### API: `currentLocale` Property
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This API documentation describes the `currentLocale` property, which holds the currently active locale. It is automatically set by a getter that runs on every translation. On the client side, it's hardcoded in production but can be automatically set from the HTML `lang` attribute or explicitly with `setDefaultLocale` in development.
```APIDOC
currentLocale: readonly string
Description: The current locale. Is automatically set by the locate getter that runs on every translation.
On the client side, in production, it is hardcoded.
During dev mode on the client it is automatically set to the `lang` attribute of the HTML tag if that's valid. You can also set it with `setDefaultLocale`.
```
--------------------------------
### Add Context to Translation Keys in JavaScript
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This JavaScript snippet demonstrates how to add contextual comments to translation keys using a colon-separated syntax. This helps translators understand the meaning or purpose of an interpolated parameter, improving translation accuracy.
```javascript
_`Greeting ${name}:name`
```
--------------------------------
### Set Locale with Cookie in Qwik onRequest Handler
Source: https://github.com/wmertens/compiled-i18n/blob/main/docs/qwik.md
This snippet demonstrates how to use the `onRequest` handler in Qwik's top layout to set the locale for the current request. It allows overriding the locale via a query parameter, which also sets a cookie, or falls back to a cookie value or the `accept-language` header.
```tsx
// ... other imports
import {guessLocale} from 'compiled-i18n'
export const onRequest: RequestHandler = async ({
query,
cookie,
headers,
locale,
}) => {
// Allow overriding locale with query param `locale`
// This sets the cookie but doesn't redirect to save another request
if (query.has('locale')) {
const newLocale = guessLocale(query.get('locale'))
cookie.delete('locale')
cookie.set('locale', newLocale, {})
locale(newLocale)
} else {
// Choose locale based on cookie or accept-language header
const maybeLocale =
cookie.get('locale')?.value || headers.get('accept-language')
locale(guessLocale(maybeLocale))
}
}
```
--------------------------------
### Server-side API Function: setLocaleGetter
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
Configures a function to dynamically retrieve the current locale for every translation request on the server. It overrides the `defaultLocale` behavior. This is particularly useful for server-side rendering (SSR) to extract the locale from the request context. This function should not be used on the client, where the locale is fixed in production.
```APIDOC
`setLocaleGetter(getLocale: () => Locale)`
Description: `getLocale` will be used to retrieve the locale on every translation. It defaults to `defaultLocale`.
Usage: For example, use this to grab the locale from context during SSR. Should not be called on the client.
```
--------------------------------
### API Function: setDefaultLocale
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
Sets the default locale at runtime, which is used when no other locale can be determined. This function is primarily beneficial during client-side development when the HTML `lang` attribute cannot be easily modified. In production client environments, this function has no effect as the locale is fixed.
```APIDOC
`setDefaultLocale(locale: string)`
Description: Sets the default locale at runtime, which is used when no locale can be determined.
Usage: Useful during dev mode on the client side if you can't change the HTML's `lang` attribute. In production on the client, the locale is fixed, and this function has no effect.
```
--------------------------------
### Define compiled-i18n JSON Data Type
Source: https://github.com/wmertens/compiled-i18n/blob/main/Readme.md
This TypeScript type definition outlines the structure of the JSON translation files. It includes the locale key, an optional fallback locale, an optional locale name, and a dictionary of translations where each entry can be a simple string or a complex Plural object.
```typescript
export type Data = {
locale: Locale // the locale key, e.g. en_US or en
fallback?: Locale // try this locale for missing keys
name?: string // the name of the locale in the locale, e.g. "Nederlands"
translations: {
[key: Key]: Translation | Plural
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.