Skip to content

A lightweight, production-ready internationalization (i18n) library with zero dependencies.

License

Notifications You must be signed in to change notification settings

minejs-org/i18n

Repository files navigation


logo


Test Coverage Github Repo Issues GitHub Repo stars

  • Overview 👀

    • Why ?

      To unify the translation system and languages ​​on the server and client, faster, cleaner, more maintainable.

    • When ?

      When you need to add a translation to your server or client.

      When you use @cruxjs/app.



  • Quick Start 🔥

    install hmm first.

    # in your terminal
    hmm i @minejs/i18n
    line
    • Setup

      • JSON

        Save the translation keys and their values ​​in .json files.

        // ./src/shared/dist/u18n/en.json
        {
            "group": {
                "key": "value"
            }
        }
        // ./src/shared/dist/u18n/ar.json
        {
            "group": {
                "key": "قيـمة"
            }
        }
      • I18n

        🌟 If you are using @cruxjs/app you can skip this step. 🌟

        Then in your project (works with any environment: server, browser, ..)

        Call the setupI18n(..) function only once in your application's lifecycle :

        import { setupI18n } from `@minejs/i18n`;
        await this.setupI18n({
            defaultLanguage     : 'en',
            supportedLanguages  : ['en', 'ar'],
            basePath            : '/static/dist/i18n',      // for client side (or your custom public url)
                                : './src/shared/dist/i18n', // for server side (or your custom local path)
        });
        line

    • Usage

      Now you can call the t(..) function anywhere in your project :

      import { t } from `@minejs/i18n`;
      t('key', { params }, fallback) // just it !
      line
      • Language Switching

        import { setLanguage, onChange } from '@minejs/i18n';
        
        // Listen to changes
        onChange((lang) => {
            console.log('Language changed to:', lang);
            document.documentElement.lang = lang;
            document.dir = isRTL() ? 'rtl' : 'ltr';
        });
        
        // Change language
        await setLanguage('ar');
      • Parameterized Translations

        {
            "greeting": "Hello {name}, you have {count} messages"
        }
        t('group.greeting', { name: 'John', count: '5' })
        // "Hello John, you have 5 messages"
      • HTML Tag Parsing

        {
            "terms": "I agree to the <link>Terms of Service</link>"
        }
        const tokens = tParse('group.terms');
        // [
        //   { type: 'text', content: 'I agree to the ' },
        //   { type: 'tag', tag: 'link', content: 'Terms of Service' }
        // ]


  • Documentation 📑

    • API

      • Types

        type LanguageCode           = string;
        interface I18nConfig {
            defaultLanguage?        : LanguageCode;
            supportedLanguages?     : LanguageCode[];
            fallbackLanguage?       : LanguageCode;
            onLanguageChange?       : (lang: LanguageCode) => void;
            storage?                : I18nStorage;
            basePath?               : string;
            fileExtension?          : string;
        }
        interface TranslationToken {
            type                    : 'text' | 'tag';
            tag?                    : string;
            content                 : string;
        }
        line
      • Functions

        • setupI18n(config)

          Initialize i18n with auto-detection

          await setupI18n({
              defaultLanguage     : 'en',
              supportedLanguages  : ['en', 'ar', 'fr'],
              basePath            : '/i18n/',  // URL (browser) or path (server)
              fileExtension       : 'json' // optional
          });
        • t(key, params?, fallback?)

          Translate with parameter replacement

          t('group.greeting', { name: 'John' }) // "Hello John"
        • tLang(lang, key, params?, fallback?)

          Translate with specific language

          tLang('group.greeting', 'ar', { name: 'أحمد' })
        • tParse(key, params?, fallback?)

          Parse translation with HTML tags

          tParse('group.message') // Returns TokenArray
        • setLanguage(lang)

          Change current language

          await setLanguage('ar')
        • getLanguage()

          Get current language code

          const lang = getLanguage() // 'en'
        • getSupportedLanguages()

          Get all supported languages

          const langs = getSupportedLanguages() // ['en', 'ar', 'fr']
        • isRTL()

          Check if current language is RTL

          if (isRTL()) { /* Handle RTL layout */ }
        • onChange(callback)

          Subscribe to language changes

          const unsubscribe = onChange((lang) => console.log('Changed to:', lang))
        • plural(count, singleKey, pluralKey)

          Handle pluralization

          plural(5, 'item.single', 'item.plural') // "5 items"
        • hasKey(key)

          Check if translation exists

          if (hasKey('settings.theme')) { /* ... */ }
        • loadLanguage(lang, translations)

          Load translations for a language

          loadLanguage('en', { greeting: 'Hello' })
        • loadTranslations(translations)

          Load multiple languages at once

          loadTranslations({
              en: { greeting: 'Hello' },
              ar: { greeting: 'مرحبا' }
          })
        line
      • Related




About

A lightweight, production-ready internationalization (i18n) library with zero dependencies.

Resources

License

Stars

Watchers

Forks