langutil
TypeScript icon, indicating that this package has built-in type declarations

4.1.0 • Public • Published

Langutil

Version Build Status Bundle size Downloads License

Works with React

Open in Visual Studio Code Support me on Ko-fi


A localization utility for JavaScript that comes with support for React and React Native.


Langutil Demo


Table of Contents


Installation/Setup

With Yarn (Recommended)

yarn add langutil

With NPM

npm i langutil

With UNPKG:

<script src="https://unpkg.com/langutil@<VERSION>/lib/umd/index.js" crossorigin></script>

Note: Replace index.js with index.min.js when deploying.


Basic Usage

Initialization

import { LangutilCore } from 'langutil'

const dictionary = {
  en: {
    GOOD_MORNING: 'Good morning',
    GOOD_MORNING_NAME: 'Good morning, {:name}.',
    GOOD_MORNING_PNAME: 'Good morning, %p.',
    GOOD_MORNING_NAME_AND_NAME: 'Good morning, {:name1} and {:name2}.',
  },
  id: {
    GOOD_MORNING: 'Selamat pagi.',
    GOOD_MORNING_NAME: 'Selamat pagi, {:name}.',
    GOOD_MORNING_PNAME: 'Selamat pagi, %p.',
    GOOD_MORNING_NAME_AND_NAME: 'Selamat pagi, {:name1} dan {:name2}.',
  },
}

const core = new LangutilCore(dictionary, 'en', { auto: true })

Set language

// With auto-detect
core.setLanguage('en', { auto: true })

// Without auto-detect
core.setLanguage('en')

Get language

core.getLanguage()
// en

Get Localized Content

Basic

core.localize('GOOD_MORNING')
// Good morning.

With Dynamic Values

// By object (Recommended for strings with multiple placeholders)
core.localize('GOOD_MORNING_NAME_AND_NAME', {
  name1: 'John',
  name2: 'Jane',
})
//  Original: Good morning, {:name1} and {:name1}.
// Localized: Good morning, John and Jane.

// By array (Recommended for strings with only one placeholder)
core.localize('GOOD_MORNING_PNAME', ['John'])
//  Original: Good morning, %p.
// Localized: Good morning, John.

Alternative Syntax

Instead of spreading the parameters, you can pass an object like this:

const localizedValue = core.localize({
  keyword: 'GOOD_MORNING_NAME_AND_NAME',
  param: {
    name1: 'John',
    name2: 'Jane',
  }
})
// Good morning, John and Jane.

Further Reading


Support Me


Package Sidebar

Install

npm i langutil

Weekly Downloads

4

Version

4.1.0

License

MIT

Unpacked Size

272 kB

Total Files

33

Last publish

Collaborators

  • glyph-cat