A tree-shakable, TypeScript-first translations library for Svelte 5 with Vite plugin support.
{{key}}
syntaxnpm install sveltekit-translations-loader
vite.config.ts
:import { sveltekitTranslationsImporterPlugin } from 'sveltekit-translations-loader';
export default defineConfig({
plugins: [
sveltekitTranslationsImporterPlugin({
defaultPath: 'src/lib/default-translations.ts',
runtimePath: 'src/lib/transhake/tGetter.ts'
})
]
});
src/lib/default-translations.ts
:const defaultTranslations = {
hello: 'Hello (default)',
goodbye: 'Goodbye (default)',
welcome: 'Welcome, {{name}}!',
'user-count': 'There are {{count}} users online',
'nested-params': 'Hello {{name}}, you have {{count}} messages'
} as const;
export default defaultTranslations;
<script lang="ts">
import * as t from '@sveltekit-translations-loader';
// or import { hello, welcome } from '@sveltekit-translations-loader';
</script>
<h1>{t.hello()}</h1><p>{t.welcome({ name: 'Anton' })}</p><p>{t.userCount({ count: 42 })}</p>
// Translation key: "hello"
t.hello(); // "Hello (default)"
// Translation key: "welcome" with value "Welcome, {{name}}!"
t.welcome({ name: 'John' }); // "Welcome, John!"
// Multiple parameters
t.nestedParams({ name: 'Alice', count: 5 });
// "Hello Alice, you have 5 messages"
// Import only what you need
import { hello, welcome } from '@sveltekit-translations-loader';
// Only these functions will be included in your bundle
console.log(hello());
console.log(welcome({ name: 'Developer' }));
// Translation key: "user-count" becomes function userCount()
t.userCount({ count: 100 }); // "There are 100 users online"
interface SvelteKitTranslationsImporterPluginOptions {
defaultPath: string; // Path to your default translations file
runtimePath: string; // Where to generate the runtime functions
}
function translationKey(params?: Record<string, string | number>): string;
Use {{key}}
syntax in your translation strings:
'Hello {{name}}, you have {{count}} messages';
Parameters are replaced at runtime:
t.message({ name: 'John', count: 3 });
// "Hello John, you have 3 messages"
// Everything bundled, even unused translations
import i18n from 'some-i18n-lib';
i18n.t('hello'); // Runtime key lookup
// Only imported functions bundled
import { hello } from '@sveltekit-translations-loader';
hello(); // Direct function call
Your translations file:
{
hello: 'Hello (default)',
'user-count': 'There are {{count}} users'
}
Generated functions:
export function hello(params?: Record<string, string | number>): string {
return 'Hello (default)';
}
export function userCount(params?: Record<string, string | number>): string {
let result = 'There are {{count}} users';
if (params?.count) {
result = result.replace(/\{\{\s*count\s*\}\}/g, String(params.count));
}
return result;
}
Contributions are welcome! Please feel free to submit a Pull Request.
MIT License - see LICENSE file for details.