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

translation-manager

v2.2.2

Published

A light, and very simple Javascript library for managing multilingual, both back and front side.

Downloads

83

Readme

translationManager

A light, and very simple Javascript library for managing multilingual, both back and front side.

node Demo

web Demo

I create an React wrapper of translationManager here

Setup:

  1. npm i translation-manager

  2. Create a folder /translations in your project (or copy translationsExample from this repo)

  3. Under this /translations folder create this tree:

    • /translations
      • /languages
        • /english
          • codes.json
          • ...any other json file
        • /french
          • codes.json
          • ...any other json file
        • ...any other language

    2.1 The files codes.json contains all the language codes used to target this language, example for english ["en","EN","en-us","en-US"]

    2.2 Next to the codes.json file you can create any other json file (with the name you want), these files will contain the translations: example:

    {
       "ADD": {
           "value": "add"
       },
       "CATEGORY": {
           "value": "category",
           "plural": "categories"
       },
       "<textCode>": {
           "value": "text",
           "<special>": "textSpecial"
       }
    }
    • you have an json-schema here

    • <special>: is any variant of your original text (plural, interrogative, ...)

  4. execute this command build-translations <path to your translations folder>, to create languageCodes.json, textCodes.json, translations.json. These three files are the compilation of the previous files.

  5. In your project, create a file initTranslations.js:

    const {TranslationManager} = require("translation-manager");
    const languageCodes        = require("translations/languageCodes");
    const translations         = require("translations/translations");
    
    TranslationManager.initData( languageCodes, translations );
    TranslationManager.setAppLanguage( "en" );
    // check Error
    if ( process.env.ENVIRONMENT !== "prod" )
        TranslationManager.verifyJson({ redundantCheck: false });

    IMPORTANT: for webpack front app: Import initTranslations.js in first, in the entrance file of your app. So that TranslationManager.initData always takes place before calling TranslationManager.getText

  6. Finish, you can use TranslationManager:

    const {TranslationManager} = require("translation-manager");
    const textCodes = require("translations/textCodes");
    
    TranslationManager.setAppLanguage( "en" );
    
    const addText      = TranslationManager.getText( textCodes.ADD );
    const categoryText = TranslationManager.getText( textCodes.CATEGORY, {special: "plural"} );
    
    console.log(`${addText} ${categoryText}`); // -> "add categories"
    TranslationManager.setAppLanguage( "fr" );
    console.log(addText + categoryText); // -> "ajouter catégories"
  7. Add shortcuts to the commands in your package.json scripts

    {
        "scripts": {
            "build-translations": "build-translations ./translations",
            "watch-translation": "watch-translations ./translations",
            "clean-translation": "clean-translations ./translations english true true"
        }
    }

Commands

build-translations

To build the translations files: languageCodes.json, textCodes.json, translations.json

$ build-translations <path_to_your_translations_folder>

clean-translations

To clean your translations files (rearrange textCodes, sort them alphabetically and can transform their case)

$ clean-translations <path_to_your_translations_folder> <base_folder_name> <organizeOtherLanguageLikeBase> <minimizeValueCase>
  • path_to_your_translations_folder: path to the translation folder
  • base_folder_name: the name of the language folder on which all cleaning will be based. textCodes of other languages will be stored in the same way as the selected language. Default is "english"
  • organizeOtherLanguageLikeBase: if you want to store textCode in the same way as the base language.
  • minimizeValueCase: if you want to transform all value in lowerCase
example:
$ clean-translations ./translations english true true

watch-translations

To watch the change in folder translations, with this command effective, any changement in translations files, trigger build-translations. It is necessary to install onchange.

$ npm i onchange --save-dev
$ watch-translations <path_to_your_translations_folder>

API

TranslationManager

[static] initData

To initialise the builded data

params:
  • languageCodes: {Object} the builded json
  • translations: {Object} the builded json
code:
TranslationManager.initData(languageCodes: Object, translations: Object)

[static] getText

To get an text

params:
  • the textCode, can be import by textCode.json (the builded file)
  • options {Object}
    • options.special: ["value"] {string} the special value from the textCode to use
    • options.option: {string} an constant string (TranslationManager.textOptions=[capitalize,capitalizeWord,capitalizeSentence,uppercase,lowercase])
    • options.language: [appLanguage] {string} to force language
    • options.insertValues: {Object} an object of insert value {key: value}, in the translation text, you have to add ${}
  • useDynamicText: [false] {boolean} if you want an TranslationText, not just a string. An TranslationText is subscribed to the language changes, it will update if you change the language, but be careful when you no longer need it, you must execute the destroy method.
return

return an instance TranslationText or a string (if forceString = true)

code:
TranslationManager.getText( textCode: String, {}, useDynamicText: boolean = false)

[static] translations

getter: get the translations initialised with initData

[static] languageCodes

getter: get the languageCodes initialised with initData

[static] getUserLanguage

only for web project, get the user locale navigator.language || navigator.userLanguage;

[static] getAppLanguage

get the current language selected in TranslationManager

[static] setAppLanguage

set the current language selected in TranslationManager

code:
TranslationManager.setAppLanguage( "fr" );

[static] onAppLanguageUpdate

to subscribe to the app language changement

params:
  • handler: {function} an function which takes the new language as first argument, and which will be executed each time app language is changed
return

return an function to unsubscribe the handler

code:
TranslationManager.onAppLanguageUpdate( handler: function)

[static] removeAppLanguageUpdate

to unsubscribe to the app language changement

params:
  • handler: {function} the previous added handler
code:
TranslationManager.removeAppLanguageUpdate( handler: function)

[static] verifyJson

To check if the translation are correct:

  • if a textcode in one language is present in all the others
  • if one textcode is not redundant with another
params:
  • redundantCheck: [true] {boolean} if you wan't a check on redondant textCode (two textCode with the same value, on same language)
code:
    TranslationManager.verifyJson(redundantCheck:boolean = true)

TranslationText

constructor

params:
  • textCode {string}: the textCode
  • options {Object}
    • options.special: ["value"] {string} the special value from the textCode to use
    • options.option: {string} an constant string (TranslationManager.textOptions=[capitalize,capitalizeWord,capitalizeSentence,uppercase,lowercase])
    • options.language: [appLanguage] {string} to force language
    • options.insertValues: {Object} an object of insert value {key: value}, in the translation text, you have to add ${}###### code:
code:
    const textCodes = require("translations/textCodes");
    myText = new TranslationText(textCodes.ADD, {special: "plural"} );

setOptions

change the internal options of the text

params:
  • options {Object}
    • options.special: ["value"] {string} the special value from the textCode to use
    • options.option: {string} an constant string (TranslationManager.textOptions=[capitalize,capitalizeWord,capitalizeSentence,uppercase,lowercase])
    • options.language: [appLanguage] {string} to force language
    • options.insertValues: {Object} an object of insert value {key: value}, in the translation text, you have to add ${}###### code:
code:
    myText.setOptions(options:Object = {} )

destroy

to destroy the current text, and unsubscribe current text to the app language change event. And avoid memory leaks

updateText

to force update the internal text

params:
  • language: [null] {string} to force language (warning: the language in options, if specified always takes priority)
code:
    myText.updateText(language:string = null )

Notes

TranslationManager.getText

TranslationManager.getText with the params useDynamicText to true, does not actually return a string, it returns an instance of the TranslationText class. TranslationText is an extends of String. But you can use it like a string, all the methods of the string class are available, you can Jsonify, concat, split, trim...

However:

  • typeof return "object"
  • if you print it, in the console, it display all the object
  • to avoid memory link, if you no longer need a text, think to do monTexte.destroy()

insertValues

You can insert values in your text, translationManager use lodash template. In your text in json file, add ${<keyName>}. When you make getText, specify insertValue option, example:

{
    "AN_ERROR_OCCURRED": {
        "value": "an error occurred: ${errorMessage}"
    }
}
const err = new Error("foobar");
TranslationManager.getText(textCode.AN_ERROR_OCCURRED, {insertValues: {errorMessage: err.message}});

Authors

License

This project is licensed under the MIT - see the LICENSE file for details