@shelchin/svelte-i18n
Version:
The last Svelte i18n library you'll ever need. Type-safe, AI-powered, zero-config.
71 lines (70 loc) • 2.37 kB
JavaScript
/**
* Library i18n configuration
* Auto-generated by @shelchin/svelte-i18n CLI
*
* This file handles translation imports and i18n setup
* Using unified API with type safety for translation keys
*/
import { createTypedUnifiedI18n, initTypedI18n, getI18nInstance } from '../unified.js';
import { PACKAGE_NAME } from '../i18n-meta.js';
// ============================================
// Auto-scan and import translations from locales directory
// ============================================
const translationModules = import.meta.glob('./locales/*.json', {
eager: true,
import: 'default'
});
const translations = {};
// Extract language code from file path and build translations object
for (const [path, module] of Object.entries(translationModules)) {
// Extract language code from path like './locales/en.json'
const match = path.match(/\/([^/]+)\.json$/);
if (match && match[1]) {
const langCode = match[1];
translations[langCode] = module;
}
}
// ============================================
// Configure and initialize i18n
// ============================================
const config = {
namespace: PACKAGE_NAME,
defaultLocale: 'en',
fallbackLocale: 'en',
translations,
interpolation: {
prefix: '{',
suffix: '}'
},
formats: {
date: { year: 'numeric', month: 'short', day: 'numeric' },
time: { hour: '2-digit', minute: '2-digit' },
number: { minimumFractionDigits: 0, maximumFractionDigits: 2 },
currency: { style: 'currency', currency: 'USD' }
}
};
// Create library i18n instance with type safety
export const libI18n = createTypedUnifiedI18n(config);
// Auto-initialize the library i18n when in browser
if (typeof window !== 'undefined') {
// Initialize asynchronously
initTypedI18n(libI18n).catch((err) => {
console.error('Failed to initialize library i18n:', err);
});
}
// Helper to get the effective i18n instance
// Try to use app's package instance if available, otherwise use library's own
export function getEffectiveLibI18n() {
try {
// Try to get the app's package instance
return getI18nInstance(PACKAGE_NAME);
}
catch {
// Fallback to library's own instance
return libI18n;
}
}
// For backward compatibility
export function getLibI18n() {
return libI18n;
}