Internationalization (i18n) library to translate texts, dates and numbers in Qwik apps
npm install qwik-speak --save-dev- Quick Start
- Tutorial: localized routing with the language
- Tutorial: translated routing with url rewriting
- Translate
- Translation functions
- Lazy loading translation
- Qwik Speak and Adapters
- Testing
Live example on Cloudflare pages and playground on CodeSandbox
import { inlineTranslate } from 'qwik-speak';
export default component$(() => {
const t = inlineTranslate();
return (
<>
<h1>{t('title@@Qwik Speak')}</h1> {/* Qwik Speak */}
<p>{t('greeting@@Hi! I am {{name}}', { name: 'Qwik Speak' })}</p> {/* Hi! I am Qwik Speak */}
</>
);
});You can pass only the default values by enabling the automatic key generation option:
import { inlineTranslate } from 'qwik-speak';
export default component$(() => {
const t = inlineTranslate();
return (
<>
<h1>{t('Qwik Speak')}</h1> {/* Qwik Speak */}
<p>{t('Hi! I am {{name}}', { name: 'Qwik Speak' })}</p> {/* Hi! I am Qwik Speak */}
</>
);
});See Translate and Automatic key generation for more details.
import { useFormatDate, useRelativeTime, useFormatNumber } from 'qwik-speak';
export default component$(() => {
const fd = useFormatDate();
const rt = useRelativeTime();
const fn = useFormatNumber();
return (
<>
<p>{fd(Date.now(), { dateStyle: 'full', timeStyle: 'short' })}</p> {/* Wednesday, July 20, 2022 at 7:09 AM */}
<p>{rt(-1, 'second')}</p> {/* 1 second ago */}
<p>{fn(1000000, { style: 'currency' })}</p> {/* $1,000,000.00 */}
</>
);
});See Localize for more details.
Translation are loaded and inlined in chunks sent to the browser during the build.
See Qwik Speak Inline Vite plugin for more information on how it works and how to use it.
To extract translations directly from the components, a command is available that automatically generates the files with the keys and default values.
See Qwik Speak Extract for more information on how to use it.
To automatically translate files, the following external packages are available:
stateDiagram-v2
State1: SpeakState
State2: SpeakConfig
State3: SpeakLocale
State4: TranslationFn
State5: Translation
State1 --> State2
State1 --> State3
State1 --> State4
State1 --> State5
note right of State2: configuration
note right of State3
- lang
- extension (Intl)
- currency
- timezone
- unit
- dir
- domain
end note
note right of State4
- loadTranslation$
end note
note right of State5
runtime assets
end note
SpeakStateis immutable: it cannot be updated after it is created and is not reactive
defaultLocaleThe default locale to use as fallbacksupportedLocalesList of locales supported by the appassetsTranslation file names. Each asset is passed to theloadTranslation$function to obtain data according to the languageruntimeAssetsAssets available at runtimekeySeparatorSeparator of nested keys. Default is.keyValueSeparatorKey-value separator. Default is@@rewriteRoutesRewrite routes as specified in Vite config forqwikCityplugindomainBasedRoutingDomain-based routing optionsshowDebugMessagesLocallyWhether to enable local debugging mode. Default is true
The SpeakLocale object contains the lang, in the format language[-script][-region], where:
languageISO 639 two-letter or three-letter codescriptISO 15924 four-letter script coderegionISO 3166 two-letter, uppercase code
and optionally contains:
extensionLanguage with Intl extensions, in the formatlanguage[-script][-region][-extensions]likeen-US-u-ca-gregory-nu-latnto format dates and numberscurrencyISO 4217 three-letter codetimeZoneFrom the IANA time zone databaseunitsKey value pairs of unit identifiersdirText direction:'ltr' | 'rtl' | 'auto'domainIn domain-based routing, set the default domain for the localewithDomainIn domain-based routing, set another domain for the locale
TranslationFn interface can be implemented to change the behavior of the library:
loadTranslation$QRL function to load translation data
Translation contains only the key value pairs of the translation data provided with the runtimeAssets
useQwikSpeak(props: QwikSpeakProps) provides the Speak context to the app. QwikSpeakProps:
configSpeak configtranslationFnOptional functions to uselangsOptional additional languages to preload data for (multilingual)currencyOptional currency if different from the current onetimeZoneOptional time zone if different from the current one
useSpeak(props: SpeakProps) can be used for lazy loading translation. SpeakProps:
assetsAssets to loadruntimeAssetsAssets to load available at runtimelangsOptional additional languages to preload data for (multilingual)
useSpeakContext()Returns the Speak stateuseSpeakConfig()Returns the configuration in Speak contextuseSpeakLocale()Returns the locale in Speak context
-
inlineTranslate: () => (keys: string | string[], params?: Record<string, any>, lang?: string)Translates a key or an array of keys. The syntax of the string iskey@@[default value] -
inlinePlural: () => (value: number | string, key?: string, params?: Record<string, any>, options?: Intl.PluralRulesOptions, lang?: string)Gets the plural by a number using Intl.PluralRules API
-
useFormatDate: () => (value: Date | number | string, options?: Intl.DateTimeFormatOptions, lang?: string, timeZone?: string)Formats a date using Intl.DateTimeFormat API -
useRelativeTime: () => (value: number | string, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions, lang?: string)Formats a relative time using Intl.RelativeTimeFormat API -
useFormatNumber: () => (value: number | string, options?: Intl.NumberFormatOptions, lang?: string, currency?: string)Formats a number using Intl.NumberFormat API -
useDisplayName: () => (code: string, options: Intl.DisplayNamesOptions, lang?: string)Returns the translation of language, region, script or currency display names using Intl.DisplayNames API
-
localizePath: () => (route: (string | URL) | string[], lang?: string)Localize a path, an URL or an array of paths with the language -
translatePath: () => (route: (string | URL) | string[], lang?: string)Translates a path, an URL or an array of paths. The translating string can be in any language. If not specified the target lang is the current one -
validateLocale(lang: string)Validatelanguage[-script][-region] -
extractFromUrl(route: URL)Extract prefix from url -
extractFromDomain(route: URL, domains: SpeakLocale[] | RewriteRouteOption[])Extract lang/prefix from domain
QwikSpeakMockProvidercomponent provides the Speak context to test enviroments
cd packages/qwik-speak
npm install
npm run buildnpm testnpm install
npm startnpm run previewnpm test
npm run test.e2enpm run devMIT