npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@telefonica/la-content-i18n

v1.1.0

Published

Library to handle localization in React apps.

Downloads

8

Readme

@telefonica/la-content-i18n

Library to handle localization in React apps.

$ npm install @telefonica/la-content-i18n

Usage

  1. Wrap your component tree in a <I18nProvider>, with the i18n attribute set to the instance resulting from init().

    languageImporter is an async function called successively with locale and namespace names. It's your responsibility to load the .json files with translations given these. It is okay to return a failing Promise if the .json file can't be found.

    import { init, I18nProvider } from '@telefonica/la-content-i18n'
    
    const i18n = init({
      languageImporter: async (locale, namespace) => import(`../locales/${locale}/${namespace}.json`),
    })
    
    export const AppWrapper = ({ children }) => <I18nProvider i18n={i18n}>{children}</I18nProvider>

    Translations will be layered. Basically, the finished strings would be something like:

    const translations = {
      ...(await languageImporter('dev', ns)),
      ...(await languageImporter('en', ns)),
      ...(await languageImporter('en-US', ns)),
    }
  2. Throughout your app, wrap any translatable strings in the <Trans> component, with an i18nKey prop identifying said string. You can also call the useTranslation() hook and the t() function it returns.

    import { Trans } from '@telefonica/la-content-i18n'
    import { MyHoverEffect } from './other-components'
    
    const MyHeader = () => (
      <div>
        <h1>
          {/* Basic usage */}
          <Trans i18nKey="myheader.welcome">Hello world!</Trans>
        </h1>
        <p>
          {/* This works! The string will reflect simple tags in the translatable messages. */}
          <Trans i18nKey="myheader.subtitle">
            Welcome to the <b>best</b> app in the world.
          </Trans>
        </p>
        <p>
          {/* This still works. More complex elements will be anonymized and be shown like `<0>this</0>`. */}
          <Trans i18nKey="myheader.call-to-action">
            Learn more about us <MyHoverEffect>now!</MyHoverEffect>
          </Trans>
        </p>
        <p>
          {/* Yep, still works! Wrap variables in an object to have it be shown as an identifier in the translatable messages. */}
          <Trans i18nKey="myheader.current-user">You're currently logged in as {{ name }}.</Trans>
        </p>
      </div>
    )

    If the <Trans> component is not enough (e.g. you need plurals), you can access a full i18next instance calling the useTranslation() hook.

  3. Call the bundled i18n binary to extract the strings from the source files. Use the -l parameter to pass a list of the desired locales.

    The default source file glob is src/**.{js,jsx,ts,tsx,mjs,cjs}, and the default output path is locales/{{locale}}/{{ns}}.json.

    $ npx i18n extract -l en,es
  4. Translate the extracted .json files

  5. Done!

Detect/change locale

With the i18n instance resulting from init() or the useTranslation() hook, you can call i18n.changeLanguage("locale"). If you don't pass a locale, one will be detected from the user's browser.

Architecture

This library is a wrapper on top of i18next and react-i18next, with some options already set by default. You can read their documentation to learn more about how it works.

This wrapper:

  • Initializes i18next and react-i18next (./src/index.ts):

    • with the browser-based language detector
    • with a custom manual backend (./src/ManualBackend.ts) that just calls a user-provided function

      Why? So the caller of the API can import() the translation files and have them handled by their bundler (i.e. webpack).

    • with automatic debugging for production
    • some more useful options (check i18next options documentation )
  • Re-exports react-i18next interfaces <Trans> and useTranslation() (the rest are not useful for our usecase) (./src/react.sx)

  • Provides a CLI for extracting translations from code into the locale files (through babel-plugin-i18next-extract) (./src/bin.ts):

    • It manually runs babel with the babel-plugin-i18next-extract plugin on the specified files, already prepared to accept the re-exported entrypoints from this package.