@sveltekit-i18n/base
v1.3.8
Published
Base functionality of sveltekit-i18n library with a support for external message parsers.
Maintainers
Readme
@sveltekit-i18n/base
Core i18n functionality for SvelteKit with support for custom message parsers. This package provides the foundation for sveltekit-i18n and can be used standalone when you need maximum flexibility with custom parsers.
When to use @sveltekit-i18n/base
Use this package if you:
- Need a custom message parser (like ICU, Fluent, or your own format)
- Want full control over message interpolation
- Are building a custom i18n solution
Use sveltekit-i18n if you:
- Want the quickest setup with sensible defaults
- Are happy with the default placeholder/modifier syntax
- Don't need custom parsers
Key Features
✅ SvelteKit ready – Full SSR and CSR support
✅ Parser-agnostic – Use any message syntax you need
✅ Custom data sources – Load translations from anywhere (files, APIs, databases)
✅ Module-based – Translations load only for visited pages
✅ Route-aware – Automatic loading based on SvelteKit routes
✅ Component-scoped – Multiple translation instances with custom definitions
✅ TypeScript – Full type support
✅ Zero dependencies – Lightweight and fast
Installation
npm install @sveltekit-i18n/baseYou'll also need a parser:
# Choose one:
npm install @sveltekit-i18n/parser-default
npm install @sveltekit-i18n/parser-icu
# or create your ownQuick Start
1. Create translation files
// src/lib/translations/en/common.json
{
"greeting": "Hello, {{name}}!",
"farewell": "Goodbye!"
}2. Setup with a parser
// src/lib/translations/index.js
import i18n from '@sveltekit-i18n/base';
import parser from '@sveltekit-i18n/parser-default';
/** @type {import('@sveltekit-i18n/base').Config} */
const config = {
parser: parser({ /* parser options */ }),
loaders: [
{
locale: 'en',
key: 'common',
loader: async () => (await import('./en/common.json')).default,
},
{
locale: 'cs',
key: 'common',
loader: async () => (await import('./cs/common.json')).default,
},
],
};
export const { t, locale, locales, loading, loadTranslations } = new i18n(config);3. Load translations in your layout
// src/routes/+layout.js
import { loadTranslations } from '$lib/translations';
/** @type {import('./$types').LayoutLoad} */
export const load = async ({ url }) => {
const { pathname } = url;
const initLocale = 'en';
await loadTranslations(initLocale, pathname);
return {};
};4. Use in components
<script>
import { t } from '$lib/translations';
</script>
<p>{$t('common.greeting', { name: 'World' })}</p>Using Different Parsers
ICU Message Format
import i18n from '@sveltekit-i18n/base';
import parser from '@sveltekit-i18n/parser-icu';
const config = {
parser: parser(),
loaders: [/* ... */],
};{
"items": "You have {count, plural, =0 {no items} one {# item} other {# items}}."
}Custom Parser
import i18n from '@sveltekit-i18n/base';
const customParser = () => ({
parse: (value, params) => {
// Your custom interpolation logic
return value.replace(/\{(\w+)\}/g, (_, key) => params[0]?.[key] ?? key);
},
});
const config = {
parser: customParser(),
loaders: [/* ... */],
};Learn more about creating custom parsers.
Configuration Options
parser (required)
Message parser instance. See Parsers.
loaders
Array of loader configurations:
loaders: [
{
locale: 'en', // Required: locale identifier
key: 'common', // Required: translation namespace
loader: async () => {}, // Required: async function returning translations
routes: ['/about'], // Optional: load only for specific routes
},
]translations
Synchronous translations loaded immediately:
translations: {
en: {
'app.name': 'My App',
},
}initLocale
Initialize with a specific locale immediately:
initLocale: 'en'fallbackLocale
Fallback when translation is missing:
fallbackLocale: 'en'Note: This loads translations for both current locale and fallback locale, which may impact performance.
fallbackValue
Default return value when translation key is not found:
fallbackValue: '...' // Default: returns the key itselfpreprocess
Transform translations after loading:
preprocess: 'full' // 'full' | 'preserveArrays' | 'none' | custom function'full'(default): Flattens all nested objects to dot notation'preserveArrays': Flattens objects but preserves arrays'none': No preprocessing- Custom function:
(input) => transformedOutput
cache
Server-side cache duration in milliseconds:
cache: 86400000 // Default: 24 hoursSet to Number.POSITIVE_INFINITY to disable cache refresh.
log
Logging configuration:
log: {
level: 'warn', // 'error' | 'warn' | 'debug'
prefix: '[i18n]: ', // Log prefix
logger: console, // Custom logger
}API Reference
Stores
t– Translation function storelocale– Current locale (writable)locales– Available locales (readable)loading– Loading state (readable)initialized– Initialization state (readable)translations– All loaded translations (readable)
Methods
loadTranslations(locale, route)– Load translations for locale and routesetLocale(locale)– Change current localesetRoute(route)– Update current route
Full API documentation: docs/README.md
Documentation
- 📖 Full API Documentation – Complete reference
- 📚 Main Library Docs – Guides, tutorials, and best practices
- 🎨 Parsers – Available parsers and how to create your own
- 💡 Examples – Real-world usage examples
TypeScript Support
import i18n, { type Config } from '@sveltekit-i18n/base';
import parser from '@sveltekit-i18n/parser-default';
import type { Config as ParserConfig } from '@sveltekit-i18n/parser-default';
const config: Config<ParserConfig> = {
parser: parser(),
loaders: [/* ... */],
};Related Packages
- sveltekit-i18n – Complete solution with default parser
- @sveltekit-i18n/parser-default – Default message parser
- @sveltekit-i18n/parser-icu – ICU message format parser
Contributing
For general contribution guidelines, see the Contributing Guide in the main library repository.
For issues specific to base functionality, create a ticket here.
Changelog
See Releases for version history.
License
MIT
