Qwik Speak Inline Vite plugin
Inline Qwik Speak
inlineTranslateandinlinePluralfunctions at compile time
How it works
On the server, translation happens at runtime: assets are loaded during SSR and the lookup also happens at runtime.
On the client, translation happens at compile-time: assets are loaded and inlined in chunks sent to the browser during the build, reducing resource usage at runtime.
runtimeAssets are always loaded at runtime, both on the server or on the client, allowing dynamic translations.
Usage
Get the code ready
Qwik uses the q:base attribute to determine the base URL for loading the chunks in the browser, so you have to set it in entry.ssr.tsx file:
import { isDev } from '@builder.io/qwik/build';
export function extractBase({ serverData }: RenderOptions): string {
if (!isDev && serverData?.locale) {
return '/build/' + serverData.locale;
} else {
return '/build';
}
}
export default function (opts: RenderToStreamOptions) {
return renderToStream(<Root />, {
manifest,
...opts,
// Determine the base URL for the client code
base: extractBase,
});
}Note. The value set through Qwik
locale()inplugin.tsis saved by Qwik inserverData.localedirectly. Make sure the locale is among thesupportedLocales
Configure
Add qwikSpeakInline Vite plugin in vite.config.ts:
Available options:
supportedLangsSupported langs. RequireddefaultLangDefault lang. RequiredbasePathThe base path. Default to'./'assetsPathPath to translation files:[basePath]/[assetsPath]/[lang]/*.json. Default to'i18n'outDirThe build output directory. Default to'dist'loadAssetsOptional function to load asset by langautoKeysAutomatically handle keys for each string. Default is falsekeySeparatorSeparator of nested keys. Default is'.'keyValueSeparatorKey-value separator. Default is'@@'
Note. Currently, only
jsonis supported as format
Now build the app:
The browser chunks are generated one for each language:
Each contains only its own translation:
dist/build/en-US/q-*.js
dist/build/it-IT/q-*.js
At the end of the build, in root folder a qwik-speak-inline.log file is generated which contains:
Missing values
Translations with dynamic keys or params
Load assets
If you need to load translation data from an external source, such as a db, you can implement a custom function with this signature:
For example:
and pass the function to loadAssets option:
The function will be called during the build for each supported language, and must return all translations for that language.
Last updated