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

i18n-for-browser

v3.0.0

Published

Modern translation module for web.

Downloads

5,358

Readme

i18n-for-browser

NPM version Dependencies status Build status Coverage status Dependabot badge Documentation badge

Modern translation module for web.

Install

npm i i18n-for-browser
# or
yarn add i18n-for-browser

CDN

i18n-for-browser is also available on unpkg.com as UMD, which exposes global object i18n.

<script src="https://unpkg.com/i18n-for-browser?main=umd"></script>

API

Module exposes next API:

export default globalConfig;
export {
    I18nConfigInstance,
    I18nPluralLocale,
    I18nLocale,
    I18nLangLocales,
    I18nLocales,
    I18nFallbacks,
    I18nUnknownPhraseListener,
    I18nProcessor,
    I18nConfig,
    I18nForkConfig,
    I18nParams,
    I18nPluralParams,
    pluralIntervalProcessor,
    mustacheProcessor,
    __,
    __mf,
    __n,
    __m
};

Description of this methods you can find in Documentation.

Shirt description:

i18n

Global config. Instanse of Config.

import i18n, {
    pluralIntervalProcessor,
    __,
    __n
} from 'i18n-for-browser';

/**
 * Set global config.
 */
i18n.configure({
    /**
     * Store of translations.
     */
    locales: {
        'en': {
            /**
             * Simple translation example.
             */
            'cat': 'cat',
            /**
             * Plutal translation example.
             */
            '%s cats': {
                'one': '%s cat',
                'other': '%s cats'
            },
            /* ... */
        },
        'ru': {
            /**
             * Пример простого перевода.
             */
            'cat': 'кошка',
            /**
             * Пример перевода множественного числа.
             */
            '%s cats': {
                'one': '%s кошка',
                'few': '%s кошки',
                'many': '%s кошек',
                'other': '%s кошка'
            },
            /* ... */
        }
    },
    /**
	 * Cookie name to store locale.
	 */
    cookieName: 'yourcookiename'
});

console.log(__('cat')); // Uses global config.

/**
 * Create config fork with some overrides. 
 */
const i18nFork = i18n.fork({
    /**
	 * List of post processors.
	 */
    processors: [pluralIntervalProcessor]
});
/**
 * Bind new config to method.
 */
const __pi = i18nFork.bind(__n);

/**
 * Now you able to use plural intervals.
 */
console.log(
    __pi('[0] no dog|[2,5] some dogs|[6,11] many dogs|[12,36] dozens of dogs|a horde of %s dogs|[100,] too many dogs', 3) // Uses bound config.
);

__()

Translates a single phrase and adds it to locales if unknown.

/**
 * Basic usage 
 */
__('cat')
/**
 * As template string
 */
__`cat`
/**
 * Supports sprintf formatting
 */
__('%d cats', 3)
/**
 * Sprintf formatting with template string
 */
__`${3} cats`
/**
 * Sprintf formatting with few arguments
 */
__('%d cats with %s', 3, 'long tails')
/**
 * Mustache templates are supported with `mustacheProcessor`
 */
__('Hello {{name}}', { name: 'Marcus' })
/**
 * First argument as object with specified locale
 */
__({ phrase: 'Hello', locale: 'ru' })

__mf()

Supports the advanced MessageFormat as provided by excellent messageformat module. You should definetly head over to messageformat.github.io for a guide to MessageFormat. i18n-for-browser takes care of new MessageFormat('en').compile(msg); with the current msg loaded from it's json files and cache that complied fn in memory. So in short you might use it similar to __() plus extra object to accomblish MessageFormat's formating.

/**
 * Basic usage, also works as raw `__` method
 */
__mf('cat')
/**
 * Basic replacement
 */
__mf('Hello {name}', { name: 'Marcus' })
/**
 * Also work with sprintf formatting
 */
__mf('Hello {name}, how was your %s?', 'test', { name: 'Marcus' })

__n()

Plurals translation of a single phrase. Singular and plural forms will get added to locales if unknown. Returns translated parsed and substituted string based on count parameter.

/**
 * Basic usage
 */
__('%s cats', 2)
/**
 * As template string
 */
__`${3} cats`
/**
 * Can work without translation in config
 */
__('%d dog', '%d dogs', 3)
/**
 * First argument as object with specified locale
 */
__n({ singular: '%s cat', plural: '%s cats', locale: 'nl', count: 3 })

__m()

Returns a map of translations for a given phrase in each language.

/**
 * Basic usage
 */
__m(__, 'Hello')

Express middleware helper

To provide translations to client from your express app you can use this helper.

import i18nExpressHelper from 'i18n-for-browser/lib/middleware';
// or 
const i18nExpressHelper = require('i18n-for-browser/lib/middleware');
// ...
// Before this `i18n` should already initialized.
app.use(i18nExpressHelper(i18nNodeConfig));
// ...
<!DOCTYPE html>
<html>
    <head>
        <title>views/layout.ejs</title>
        <%- initI18nForBrowser() %>
        <script src="js-file-with-imported-i18n-for-browser.js"></script>
    </head>
    <body>
        <%- body %>
    </body>
</html>