### Installation and Running sveltekit-i18n Examples Source: https://github.com/sveltekit-i18n/lib/blob/master/examples/README.md Instructions on how to set up and run the sveltekit-i18n examples. This involves cloning the repository, installing dependencies, and starting the development server. ```bash git clone # or download the project cd ./your/example/destination/ npm i sveltekit-i18n@latest npm run dev -- --open ``` -------------------------------- ### Setup and Run Demo Source: https://github.com/sveltekit-i18n/lib/blob/master/examples/parser-icu/README.md Follow these steps to download the example, install dependencies, and start the development server for the @sveltekit-i18n/parser-icu demo. ```shell cd ./parser-icu/ npm i npm run dev -- --open ``` -------------------------------- ### sveltekit-i18n Configuration Options Source: https://github.com/sveltekit-i18n/lib/blob/master/examples/README.md Demonstrates key configuration options for sveltekit-i18n, including loaders for translation files and preprocess directives for managing translation loading and compilation. ```APIDOC sveltekit-i18n Configuration: Configuration object for sveltekit-i18n. Properties: - loaders: Array of loader objects. Each loader specifies a locale and a path to its translation data. Example: [ { "locale": "en", "key": "common", "loader": async () => (await import("./en/common.json")).default }, { "locale": "en", "key": "home", "loader": async () => (await import("./en/home.json")).default }, { "locale": "de", "key": "common", "loader": async () => (await import("./de/common.json")).default }, { "locale": "de", "key": "home", "loader": async () => (await import("./de/home.json")).default } ] - preprocess: Array of preprocess objects. These are used to process translation files before they are loaded. Example: [ { "pattern": "*.{json,json5}", "preprocessor": "parser-default" }, { "pattern": "*.{json,json5}", "preprocessor": "parser-icu" } ] - fallbackLocale: Specifies the fallback locale to use when a translation is not found in the current locale. Example: "en" ``` -------------------------------- ### Parser Integration Examples Source: https://github.com/sveltekit-i18n/lib/blob/master/examples/README.md Examples showcasing the integration of different parsers with sveltekit-i18n. This includes the default parser and the ICU parser, demonstrating how to handle various translation syntaxes. ```APIDOC sveltekit-i18n Parsers: Parsers are used to process translation files, enabling different syntax features. 1. Default Parser: - Used for standard JSON translation files. - Configuration: `preprocess: [{ "pattern": "*.{json,json5}", "preprocessor": "parser-default" }]` - Example Usage: Loads JSON files directly. 2. ICU Parser: - Used for translations following the ICU message syntax, supporting complex formatting like plurals and genders. - Configuration: `preprocess: [{ "pattern": "*.{json,json5}", "preprocessor": "parser-icu" }]` - Example Usage: Handles messages like `items_count: {count, plural, =0 {no items} =1 {one item} other {# items}}` ``` -------------------------------- ### Setup sveltekit-i18n Translations Configuration (JavaScript) Source: https://github.com/sveltekit-i18n/lib/blob/master/README.md Configures the sveltekit-i18n library with locale definitions, keys, and loaders. It specifies how translations are loaded for different locales and routes, enabling dynamic translation management. ```javascript import i18n from 'sveltekit-i18n'; /** @type {import('sveltekit-i18n').Config} */ const config = ({ loaders: [ { locale: 'en', key: 'common', loader: async () => ( await import('./en/common.json') ).default, }, { locale: 'en', key: 'home', routes: ['/'], // you can use regexes as well! loader: async () => ( await import('./en/home.json') ).default, }, { locale: 'en', key: 'about', routes: ['/about'], loader: async () => ( await import('./en/about.json') ).default, }, { locale: 'cs', key: 'common', loader: async () => ( await import('./cs/common.json') ).default, }, { locale: 'cs', key: 'home', routes: ['/'], loader: async () => ( await import('./cs/home.json') ).default, }, { locale: 'cs', key: 'about', routes: ['/about'], loader: async () => ( await import('./cs/about.json') ).default, }, ], }); export const { t, locale, locales, loading, loadTranslations } = new i18n(config); ``` -------------------------------- ### SvelteKit Custom Parameter Matcher for Locale Source: https://github.com/sveltekit-i18n/lib/blob/master/examples/locale-router-advanced/README.md The `locale.js` parameter matcher in `src/params/` defines how the `[...lang=locale]` route parameter is handled. It allows routing for pages starting with a locale prefix or the default language index. ```javascript /** @type {import('@sveltejs/kit').ParamMatcher} */ export function locale(param) { // Matches 'en', 'de', 'cs' or the root path for default language return /^(en|de|cs)$/.test(param) || param === ''; } ``` -------------------------------- ### sveltekit-i18n Configuration Options Source: https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md Defines the various configuration properties for the sveltekit-i18n library. This includes settings for translations, asynchronous loading of translation data, preprocessing steps, locale fallback mechanisms, caching behavior, logging levels and prefixes, and parser-specific options. ```APIDOC Config: translations?: Translations.T This property defines translations, which should be in place before `loaders` will trigger. It's useful for synchronous translations (e.g. locally defined language names which are same for all language mutations). loaders?: Loader.LoaderModule[] You can use `loaders` to define your asyncronous translation load. All loaded data are stored so loader is triggered only once – in case there is no previous version of the translation. It can get refreshed according to `config.cache`. Each loader can include: locale: string – locale (e.g. `en`, `de`) which is this loader for. key: string – represents the translation namespace. This key is used as a translation prefix so it should be module-unique. You can access your translation later using `$t('key.yourTranslation')`. It shouldn't include `.` (dot) character. loader: () => Promise> – is a function returning a `Promise` with translation data. You can use it to load files locally, fetch it from your API etc... routes?: Array – can define routes this loader should be triggered for. You can use Regular expressions too. For example `[//.ome/]` will be triggered for `/home` and `/rome` route as well (but still only once). Leave this `undefined` in case you want to load this module with any route (useful for common translations). preprocess?: 'full' | 'preserveArrays' | 'none' | (input: Translations.Input) => any Defines a preprocess strategy or a custom preprocess function. Preprocessor runs immediately after the translation data load. Examples for input: ```json {"a": {"b": [{"c": {"d": 1}}, {"c": {"d": 2}}]}} ``` `'full'` (default) setting will result in: ```json {"a.b.0.c.d": 1, "a.b.1.c.d": 2} ``` `'preserveArrays'` in: ```json {"a.b": [{"c.d": 1}, {"c.d": 2}]} ``` `'none'` (nothing's changed): ```json {"a": {"b": [{"c": {"d": 1}}, {"c": {"d": 2}}]}} ``` Custom preprocess function `(input) => JSON.parse(JSON.stringify(input).replace('1', '"🦄"'))` will output: ```json {"a": {"b": [{"c": {"d": "🦄"}}, {"c": {"d": 2}}]}} ``` initLocale?: string If you set this property, translations will be initialized immediately using this locale. fallbackLocale?: string If you set this property, translations are automatically loaded not for current `$locale` only, but for this locale as well. In case there is no translation for current `$locale`, fallback locale translation is used instead of translation key placeholder. This is also used as a fallback when unknown locale is set. Note that it's not recommended to use this property if you don't really need it. It may affect your data load. fallbackValue?: any By default, translation key is returned in case no translation is found for given translation key. For example, `$t('unknown.key')` will result in `'unknown.key'` output. You can set this output value using this config prop. cache?: number When you are serving your app, translations are loaded only once on server. This property allows you to setup a refresh period in milliseconds when your translations are refetched on the server. The default value is `86400000` (24 hours). Tip: You can set to `Number.POSITIVE_INFINITY` to disable server-side refreshing. log.level?: 'error' | 'warn' | 'debug' You can manage log level using this property (default: `'warn'`). log.prefix?: string You can prefix output logs using this property (default: `'[i18n]: '`). log.logger?: Logger.T You can setup your custom logger using this property (default: `console`). parserOptions?: Parser.Options This property includes configuration related to `@sveltekit-i18n/parser-default`. Read more about `parserOptions` [here](https://github.com/sveltekit-i18n/parsers/tree/master/parser-default#options). ``` -------------------------------- ### Apache .htaccess for Locale Routing and Error Handling Source: https://github.com/sveltekit-i18n/lib/blob/master/examples/locale-router-static/README.md Configuration for Apache web servers to handle locale-based URL routing and serve language-specific error pages. It redirects users to appropriate language subdirectories based on the Accept-Language header and sets custom error documents for each locale. ```apache-config RewriteEngine On RewriteBase / # DirectorySlash Off # Prevent dot directories (hidden directories like .git) to be exposed to the public # Except for the .well-known directory used by LetsEncrypt a.o # RewriteRule "/\.|^\.(?!well-known/)" - [F] # Rewrite www.example.com -> example.com -- used with SEO Strict URLs plugin # RewriteCond %{HTTP_HOST} . # RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC] # RewriteRule ^(.*)$ https://%1/$1 [R=301,L] # Rewrite secure requests properly to prevent SSL cert warnings, e.g. prevent # https://www.example.com when your cert only allows https://secure.example.com # RewriteCond %{SERVER_PORT} !^443 # RewriteRule (.*) https://%{SERVER_NAME}/$1 [R=301,L] # Remove trailing slashes # NOTE: Use with `DirectorySlash Off`. # RewriteCond %{REQUEST_FILENAME} !-f # RewriteRule ^(.*[^/])$ /$1/ [L] # Serve files if exist RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^(.*)$ - [L] ############################################## # Skip redirection if locale already present # ############################################## RewriteRule ^cs(\/.*)?$ - [L] RewriteRule ^de(\/.*)?$ - [L] RewriteRule ^en(\/.*)?$ - [L] ############################## # Set custom locales if fits # ############################## RewriteCond %{HTTP:Accept-Language} ^cs [NC] RewriteRule ^ /cs%{REQUEST_URI} [R=301,L] RewriteCond %{HTTP:Accept-Language} ^de [NC] RewriteRule ^ /de%{REQUEST_URI} [R=301,L] ############################################### # Set default locale if no custom locale fits # ############################################### RewriteRule ^ /en%{REQUEST_URI} [R=301,L] ###################################### # Set error pages for custom locales # ###################################### ErrorDocument 401 /cs/401/index.html ErrorDocument 403 /cs/403/index.html ErrorDocument 404 /cs/404/index.html ErrorDocument 500 /cs/500/index.html ErrorDocument 401 /de/401/index.html ErrorDocument 403 /de/403/index.html ErrorDocument 404 /de/404/index.html ErrorDocument 500 /de/500/index.html ################################## # Set default locale error pages # ################################## ErrorDocument 401 /en/401/index.html ErrorDocument 403 /en/403/index.html ErrorDocument 404 /en/404/index.html ErrorDocument 500 /en/500/index.html ``` -------------------------------- ### SvelteKit Server Hook for Locale Redirection Source: https://github.com/sveltekit-i18n/lib/blob/master/examples/locale-router-advanced/README.md The `hooks.server.js` file manages server-side logic for locale routing. It handles redirects to the appropriate language mutation and fetches pages with the default language in the background, serving them without a lang prefix in the URL. ```javascript /** @type {import('@sveltejs/kit').Handle} */ export async function handle({ event, resolve }) { const lang = event.url.pathname.split('/')[1]; // If no language prefix is found, redirect to default language (e.g., '/en') if (!lang || !['en', 'de', 'cs'].includes(lang)) { return new Response('Redirecting to default language', { status: 307, headers: { 'Location': `/en${event.url.pathname}` } }); } // If language prefix is present and valid, proceed with the request const response = await resolve(event); return response; } ``` -------------------------------- ### Load Translations in SvelteKit Layout (JavaScript) Source: https://github.com/sveltekit-i18n/lib/blob/master/README.md Loads translations for the current locale and path within a SvelteKit application's layout. This ensures translations are available before components render, typically based on the user's locale and the current URL. ```javascript import { loadTranslations } from '$lib/translations'; /** @type {import('@sveltejs/kit').Load} */ export const load = async ({ url }) => { const { pathname } = url; const initLocale = 'en'; // get from cookie, user session, ... await loadTranslations(initLocale, pathname); // keep this just before the `return` return {}; } ``` -------------------------------- ### Use Translations in Svelte Components (Svelte) Source: https://github.com/sveltekit-i18n/lib/blob/master/README.md Integrates the translation function `t` from sveltekit-i18n into Svelte components. It allows displaying translated strings and using placeholders or modifiers defined in the translation files. ```svelte

{$t('common.page', { pageName })}

{$t('home.content')}

``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.