Git Product home page Git Product logo

val-i18n's Introduction

Build Status npm-version Coverage Status minified-size

Commitizen friendly Conventional Commits code style: prettier

Reactive i18n with val-i18n.

Install

npm add val-i18n value-enhancer

Features

  • Subscribable reactive lang$, t$ and locales$.
  • Lightweight and fast t() translation.
  • Nested locale messages.
  • Message formatting and pluralization.
  • Easy dynamic locale loading.
  • Locale namespaces.
  • Framework integration friendly (React, Svelte, etc.).

Usage

Create an I18n instance with static locales:

import { I18n, type Locales } from "val-i18n";

const locales: Locales = {
  en: {
    stock: {
      fruit: "apple",
    },
  },
};

const i18n = new I18n("en", locales);
i18n.t("stock.fruit"); // apple

// add more locales later
const zhCN = await import(`./locales/zh-CN.json`);
i18n.addLocale("zh-CN", zhCN);

// or replace all locales manually
const zhTW = await import(`./locales/zh-TW.json`);
i18n.locales$.set({ "zh-TW": zhTW });

You can also create an I18n instance with preloaded dynamic locales:

import { I18n } from "val-i18n";

const i18n = await I18n.preload("en", lang => import(`./locales/${lang}.json`));
// Locale `./locales/en.json` is preloaded

await i18n.switchLang("zh-CN"); // Locale `./locales/zh-CN.json` is loaded

Detect Language

You can detect language of browser/nodejs via detectLang. BCP 47 tags and sub-tags are supported.

import { detectLang } from "val-i18n";

detectLang(); // "en-US"

const i18n = await I18n.preload(
  // language sub-tag is matched
  detectLang(["en", "zh-CN"]) || "zh-TW", // "en"
  lang => import(`./locales/${lang}.json`)
);

Message Formatting

Message keys are surrounded by double curly brackets:

import { I18n, type Locales } from "val-i18n";

const locales: Locales = {
  en: {
    stock: {
      fruit: "apple",
    },
    fav_fruit: "I love {{fruit}}",
  },
};

const i18n = new I18n("en", locales);
const fruit = i18n.t("stock.fruit"); // apple
i18n.t("fav_fruit", { fruit }); // I love apple

It also works with array:

import { I18n, type Locales } from "val-i18n";

const locales: Locales = {
  en: {
    fav_fruit: "I love {{0}} and {{1}}",
  },
};

const i18n = new I18n("en", locales);
i18n.t("fav_fruit", ["apple", "banana"]); // I love apple and banana

Pluralization

Message formatting supports a special key :option whose value will be appended to the key-path.

For example:

i18n.t("a.b.c", { ":option": "d" });

It will look for "a.b.c.d" and fallback to "a.b.c.other" if not found.

So for pluralization we can simply use :option as number count.

import { I18n, type Locales } from "val-i18n";

const locales: Locales = {
  en: {
    apples: {
      0: "No apple",
      1: "An apple",
      other: "{{:option}} apples",
    },
  },
};

const i18n = new I18n("en", locales);
i18n.t("apples", { ":option": 0 }); // No apple
i18n.t("apples", { ":option": 1 }); // An apple
i18n.t("apples", { ":option": 3 }); // 3 apples

Reactive I18n

i18n.lang$, i18n.t$ and i18n.locales$ are subscribable values.

See value-enhancer for more details.

i18n.lang$.reaction(lang => {
  // logs lang on changed
  console.log(lang);
});

i18n.lang$.subscribe(lang => {
  // logs lang immediately and on changed
  console.log(lang);
});

Namespace

I18n instance is cheap to create. You can create multiple instances for different namespaces.

import { I18n } from "val-i18n";

// Module Login
async function moduleLogin() {
  const i18n = await I18n.preload(
    "en",
    lang => import(`./locales/login/${lang}.json`)
  );

  console.log(i18n.t("password"));
}

// Module About
async function moduleAbout() {
  const i18n = await I18n.preload(
    "en",
    lang => import(`./locales/about/${lang}.json`)
  );

  console.log(i18n.t("author"));
}

Hot Module Replacement

To use Vite HMR for locales:

const i18n = await I18n.preload("en", lang => import(`./locales/${lang}.json`));

if (import.meta.hot) {
  import.meta.hot.accept(
    ["./locales/en.json", "./locales/zh-CN.json"],
    ([en, zhCN]) => {
      i18n.locales$.set({
        ...i18n.locales,
        en: en?.default || i18n.locales.en,
        "zh-CN": zhCN?.default || i18n.locales["zh-CN"],
      });
    }
  );
}

Dynamic Import

Although you can simply use import() to dynamically load locales, with bundler API you can do more.

For example with Vite you can use glob import to statically get info of all locales. This way allows you to add or remove locales without changing source code.

import { I18n, detectLang, type Locale, type LocaleLang } from "val-i18n";

export const i18nLoader = (): Promise<I18n> => {
  const localeModules = import.meta.glob<boolean, string, Locale>(
    "./locales/*.json",
    { import: "default" }
  );

  const localeLoaders = Object.keys(localeModules).reduce((loaders, path) => {
    if (localeModules[path]) {
      const langMatch = path.match(/\/([^/]+)\.json$/);
      if (langMatch) {
        loaders[langMatch[1]] = localeModules[path];
      }
    }
    return loaders;
  }, {} as Record<LocaleLang, () => Promise<Locale>>);

  const langs = Object.keys(localeLoaders);

  return I18n.preload(
    detectLang(langs) || (localeLoaders.en ? "en" : langs[0]),
    lang => localeLoaders[lang]()
  );
};

Framework Integration

Svelte

In Svelte you can just pass i18n.t$ as component props and use $t directly.

<script>
  export let t;
</script>

<div>
  <h1>{$t("title")}</h1>
</div>
new MySvelteComponent({
  target: document.body,
  props: {
    t: i18n.t$,
  },
});

You can also set i18n.t$ to a Svelte context.

For more advance usages checkout val-i18n-svelte.

React

It is recommended to also install val-i18n-react which includes some handy hooks.

Or you can just use the hooks for value-enhancer: use-value-enhancer.

val-i18n's People

Contributors

crimx avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar

val-i18n's Issues

Docs: hot reload example

It is possible to use i18n with hot-reload, one way is to ensure the dependency graph of the i18n module does not bubble up to the entry point, instead it only bubbles up to components (which are so-called side effect boundaries). Here's the sample code stolen from https://github.com/intlify/vue-i18n-next/blob/-/docs-old/guide/hot-reload.md but was adapted to Vite.

// src/service/i18n.ts
import en from './en.json'
import zhCN from './zh-CN.json'
import { I18n } from 'val-i18n'

export const i18n = new I18n("en", { en, 'zh-CN': zhCN })

export const lang = i18n.lang$
export const t = i18n.t$

if (import.meta.hot) {
  import.meta.hot.accept(['./en.json', './zh-CN.json'], async function () {
    // Note: to make import analyzing work, we must use template string literals.
    i18n.addLocale('en', await import(`./en.json?t=${Date.now()}`).then(m => m.default))
    i18n.addLocale('zh-CN', await import(`./zh-CN.json?t=${Date.now()}`).then(m => m.default))
  })
}
<!-- src/App.svelte -->
<script lang="ts">
  import { lang, t } from './service/i18n'
  let name = "world"
</script>

<main>
  <input bind:value={name}>
  <select bind:value={$lang}>
    <option value="en">English</option>
    <option value="zh-CN">Simplified Chinese</option>
  </select>
  <h1>{$t('hello', { name })}</h1>
</main>

React sample should be similar by using val-i18n-react.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.