cibernox / svelte-intl-precompile

I18n library for Svelte.js that analyzes your keys at build time for max performance and minimal footprint
https://svelte-intl-precompile.com
ISC License
274 stars 13 forks source link

Different language codes for same language #6

Closed fabianmossberg closed 3 years ago

fabianmossberg commented 3 years ago

There are multiple ways to write a language code.

I used this library and logged what languages my visitors had.

en-US
en-GB
en
sv-se
sv-SE
sv

When registering the languages:

addMessages('en', en);

It would be nice to have that one match en*, or at least to add an array addMessages(['en', 'en-GB', 'en-US', 'en-AU', 'en-BZ', 'en-CA', 'en-IE', 'en-JM', 'en-NZ', 'en-ZA', 'en-TT', en);

I solved it by writing my own getLocaleFromNavigator that slices the first two characters, removing the country specific codes.

const customGetLocaleFromNavigator = () => {
    if (typeof window === 'undefined') return null;
    return (window.navigator.language || window.navigator.languages[0]).slice(0, 2);
};
cibernox commented 3 years ago

Unless I misunderstood what you're saying, I'd say that the library already behaves like you want.

When you set the locale of the library with any method (e.g. passing initialLocale: getLocaleFromNavigator(), to init), that locale string (e.g. en-AU) the library will try to use the dictionary of locales named "en-AU", but if that is not defined it will default to just "en".

Take the following initialization code.

import { addMessages, init, getLocaleFromNavigator } from 'svelte-intl-precompile';
import en from '../../locales/en.js';
import enUS from '../../locales/en-us.js';
// import enGB from '../../locales/en-gb.js';

addMessages('en', en)
addMessages('en-US', enUS)
// addMessages('en-GB', enGB)

If your browsers locale is en-US, it will use the translations defined in en-us.js. If your locale is en-GB since there's no en-GB messages dictionary, it will fallback to just en.

That way you can define a single universal english translations for all local variants if you want.

cibernox commented 3 years ago

I'm closing this, let me know if you still struggle with locale variants