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

1.3.7 • Public • Published

example workflow Static Badge Default Project npm Coverage Status

Install

npm install i18n-trivial --save-dev

Usage

Here's an example, You can also clone this project and run npm run dev

API

import { i18n, I18nProvider, useI18n, withTranslation } from "i18n-trivial";
i18n

You need to execute i18n.use(config) before the root component render

  • languageOptions?: Record<string, string>;
  • initialLanguage?: string;
  • initialNamespace?: string;
  • cache?: Record<string, any>;
i18n.use({
languageOptions: {
  en: '英语',
  cn: '中文',
  },
  initialLanguage: 'cn',
  initialNamespace: 'common',
  cache: {
    en: require('./locales/en.json'),
    cn: require('./locales/cn.json'),
  },
})

Note: You can set the parameter '?lang=cn' at the end of the URL, indicating that the current default language is Chinese. The 'initialLanguage' will be automatically detected. If not specified, it will default to the browser's language. If the specified language doesn't exist, you will receive a warning.

I18nProvider

You need to wrap the project root component with the <I18nProvider>

  <I18nProvider>
    <App />
  </I18nProvider>
useI18n
function App() {
  const { t, changeLanguage, currentLanguage } = useI18n(namespace?)
  return (
    <div className="App">
      {t("name")}
    </div>
  );
}
export default App;
withTranslation
function App({ t }) {
  return (
    <div className="App">
      {t("name")}
    </div>
  );
}

export default withTranslation(App, namespace?);

Note: If you configured initialNamespace, this property will be read automatically when using withTranslation

t
{t("address", { city: "xian" })}
{t('apples', {_count: 3})}
  • key: string
  • payload?: any

translation source example

Please follow the format below to create the translation file, please note that common is a namespace, you can also ignore this parameter, if you do not want to use the namespace, and _count is a unique attribute, used to do simple and complex, do not use other

{
  "common": {
    "name": "yixiang",
    "address": "i'm in {city}",
    "apples": {
      "one": "{_count} apple",
      "other": "{_count} apples"
    }
  }
}
{
  "name": "yixiang",
  "address": "city: {city}"
}

Contributing

Please submit a pull request to me

Package Sidebar

Install

npm i i18n-trivial

Weekly Downloads

8

Version

1.3.7

License

MIT

Unpacked Size

16.4 kB

Total Files

14

Last publish

Collaborators

  • ilvseyinfu