React / Redux and Multilingual (Internationalization) Apps - Architecture

后端 未结 7 1268
挽巷
挽巷 2020-12-04 04:43

I\'m building an app that will need to be available in multiple languages and locales.

My question is not purely technical, but rather about the architecture, and th

相关标签:
7条回答
  • 2020-12-04 05:03

    From my experience the best approach is to create an i18n redux state and use it, for many reasons:

    1- This will allow you to pass the initial value from the database, local file or even from a template engine such as EJS or jade

    2- When the user changes the language you can change the whole application language without even refreshing the UI.

    3- When the user changes the language this will also allow you to retrieve the new language from API, local file or even from constants

    4- You can also save other important things with the strings such as timezone, currency, direction (RTL/LTR) and list of available languages

    5- You can define the change language as a normal redux action

    6- You can have your backend and front end strings in one place, for example in my case I use i18n-node for localization and when the user changes the UI language I just do a normal API call and in the backend, I just return i18n.getCatalog(req) this will return all the user strings only for the current language

    My suggestion for the i18n initial state is:

    {
      "language":"ar",
      "availableLanguages":[
        {"code":"en","name": "English"},
        {"code":"ar","name":"عربي"}
      ],
      "catalog":[
         "Hello":"مرحباً",
         "Thank You":"شكراً",
         "You have {count} new messages":"لديك {count} رسائل جديدة"
       ],
      "timezone":"",
      "currency":"",
      "direction":"rtl",
    }
    

    Extra useful modules for i18n:

    1- string-template this will allow you to inject values in between your catalog strings for example:

    import template from "string-template";
    const count = 7;
    //....
    template(i18n.catalog["You have {count} new messages"],{count}) // لديك ٧ رسائل جديدة
    

    2- human-format this module will allow you to converts a number to/from a human readable string, for example:

    import humanFormat from "human-format";
    //...
    humanFormat(1337); // => '1.34 k'
    // you can pass your own translated scale, e.g: humanFormat(1337,MyScale)
    

    3- momentjs the most famous dates and times npm library, you can translate moment but it already has a built-in translation just you need to pass the current state language for example:

    import moment from "moment";
    
    const umoment = moment().locale(i18n.language);
    umoment.format('MMMM Do YYYY, h:mm:ss a'); // أيار مايو ٢ ٢٠١٧، ٥:١٩:٥٥ م
    

    Update (14/06/2019)

    Currently, there are many frameworks implement the same concept using react context API (without redux), I personally recommended I18next

    0 讨论(0)
  • 2020-12-04 05:09

    I would like to propose a simple solution using create-react-app.

    The application will be built for every language separately, therefore whole translation logic will be moved out of the application.

    The web server will serve the correct language automatically, depending on Accept-Language header, or manually by setting a cookie.

    Mostly, we do not change language more than once, if ever at all)

    Translation data put inside same component file, that uses it, along styles, html and code.

    And here we have fully independent component that responsible for its own state, view, translation:

    import React from 'react';
    import {withStyles} from 'material-ui/styles';
    import {languageForm} from './common-language';
    const {REACT_APP_LANGUAGE: LANGUAGE} = process.env;
    export let language; // define and export language if you wish
    class Component extends React.Component {
        render() {
            return (
                <div className={this.props.classes.someStyle}>
                    <h2>{language.title}</h2>
                    <p>{language.description}</p>
                    <p>{language.amount}</p>
                    <button>{languageForm.save}</button>
                </div>
            );
        }
    }
    const styles = theme => ({
        someStyle: {padding: 10},
    });
    export default withStyles(styles)(Component);
    // sets laguage at build time
    language = (
        LANGUAGE === 'ru' ? { // Russian
            title: 'Транзакции',
            description: 'Описание',
            amount: 'Сумма',
        } :
        LANGUAGE === 'ee' ? { // Estonian
            title: 'Tehingud',
            description: 'Kirjeldus',
            amount: 'Summa',
        } :
        { // default language // English
            title: 'Transactions',
            description: 'Description',
            amount: 'Sum',
        }
    );
    

    Add language environment variable to your package.json

    "start": "REACT_APP_LANGUAGE=ru npm-run-all -p watch-css start-js",
    "build": "REACT_APP_LANGUAGE=ru npm-run-all build-css build-js",
    

    That is it!

    Also my original answer included more monolithic approach with single json file for each translation:

    lang/ru.json

    {"hello": "Привет"}
    

    lib/lang.js

    export default require(`../lang/${process.env.REACT_APP_LANGUAGE}.json`);
    

    src/App.jsx

    import lang from '../lib/lang.js';
    console.log(lang.hello);
    
    0 讨论(0)
  • 2020-12-04 05:10

    If not yet done having a look at https://react.i18next.com/ might be a good advice. It is based on i18next: learn once - translate everywhere.

    Your code will look something like:

    <div>{t('simpleContent')}</div>
    <Trans i18nKey="userMessagesUnread" count={count}>
      Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
    </Trans>
    

    Comes with samples for:

    • webpack
    • cra
    • expo.js
    • next.js
    • storybook integration
    • razzle
    • dat
    • ...

    https://github.com/i18next/react-i18next/tree/master/example

    Beside that you should also consider workflow during development and later for your translators -> https://www.youtube.com/watch?v=9NOzJhgmyQE

    0 讨论(0)
  • 2020-12-04 05:17

    From my research into this there appears to be two main approaches being used to i18n in JavaScript, ICU and gettext.

    I've only ever used gettext, so I'm biased.

    What amazes me is how poor the support is. I come from the PHP world, either CakePHP or WordPress. In both of those situations, it's a basic standard that all strings are simply surrounded by __(''), then further down the line you get translations using PO files very easily.

    gettext

    You get the familiarity of sprintf for formatting strings and PO files will be translated easily by thousands of different agencies.

    There's two popular options:

    1. i18next, with usage described by this arkency.com blog post
    2. Jed, with usage described by the sentry.io post and this React+Redux post,

    Both have gettext style support, sprintf style formatting of strings and import / export to PO files.

    i18next has a React extension developed by themselves. Jed doesn't. Sentry.io appear to use a custom integration of Jed with React. The React+Redux post, suggests using

    Tools: jed + po2json + jsxgettext

    However Jed seems like a more gettext focussed implementation - that is it's expressed intention, where as i18next just has it as an option.

    ICU

    This has more support for the edge cases around translations, e.g. for dealing with gender. I think you will see the benefits from this if you have more complex languages to translate into.

    A popular option for this is messageformat.js. Discussed briefly in this sentry.io blog tutorial. messageformat.js is actually developed by the same person that wrote Jed. He makes quite stong claims for using ICU:

    Jed is feature complete in my opinion. I am happy to fix bugs, but generally am not interested in adding more to the library.

    I also maintain messageformat.js. If you don't specifically need a gettext implementation, I might suggest using MessageFormat instead, as it has better support for plurals/gender and has built-in locale data.

    Rough comparison

    gettext with sprintf:

    i18next.t('Hello world!');
    i18next.t(
        'The first 4 letters of the english alphabet are: %s, %s, %s and %s', 
        { postProcess: 'sprintf', sprintf: ['a', 'b', 'c', 'd'] }
    );
    

    messageformat.js (my best guess from reading the guide):

    mf.compile('Hello world!')();
    mf.compile(
        'The first 4 letters of the english alphabet are: {s1}, {s2}, {s3} and {s4}'
    )({ s1: 'a', s2: 'b', s3: 'c', s4: 'd' });
    
    0 讨论(0)
  • 2020-12-04 05:21

    Antoine's solution works fine, but have some caveats :

    • It uses the React context directly, which I tend to avoid when already using Redux
    • It imports directly phrases from a file, which can be problematic if you want to fetch needed language at runtime, client-side
    • It does not use any i18n library, which is lightweight, but doesn't give you access to handy translation functionalities like pluralization and interpolation

    That's why we built redux-polyglot on top of both Redux and AirBNB's Polyglot.
    (I'm one of the authors)

    It provides :

    • a reducer to store language and corresponding messages in your Redux store. You can supply both by either :
      • a middleware that you can configure to catch specific action, deduct current language and get/fetch associated messages.
      • direct dispatch of setLanguage(lang, messages)
    • a getP(state) selector that retrieves a P object that exposes 4 methods :
      • t(key): original polyglot T function
      • tc(key): capitalized translation
      • tu(key): upper-cased translation
      • tm(morphism)(key): custom morphed translation
    • a getLocale(state)selector to get current language
    • a translate higher order component to enhance your React components by injecting the p object in props

    Simple usage example :

    dispatch new language :

    import setLanguage from 'redux-polyglot/setLanguage';
    
    store.dispatch(setLanguage('en', {
        common: { hello_world: 'Hello world' } } }
    }));
    

    in component :

    import React, { PropTypes } from 'react';
    import translate from 'redux-polyglot/translate';
    
    const MyComponent = props => (
      <div className='someId'>
        {props.p.t('common.hello_world')}
      </div>
    );
    MyComponent.propTypes = {
      p: PropTypes.shape({t: PropTypes.func.isRequired}).isRequired,
    }
    export default translate(MyComponent);
    

    Please tell me if you have any question/suggestion !

    0 讨论(0)
  • 2020-12-04 05:24

    After trying quite a few solutions, I think I found one that works well and should be an idiomatic solution for React 0.14 (i.e. it doesn't use mixins, but Higher Order Components) (edit: also perfectly fine with React 15 of course!).

    So here the solution, starting by the bottom (the individual components):

    The Component

    The only thing your component would need (by convention), is a strings props. It should be an object containing the various strings your Component needs, but really the shape of it is up to you.

    It does contain the default translations, so you can use the component somewhere else without the need to provide any translation (it would work out of the box with the default language, english in this example)

    import { default as React, PropTypes } from 'react';
    import translate from './translate';
    
    class MyComponent extends React.Component {
        render() {
    
            return (
                 <div>
                    { this.props.strings.someTranslatedText }
                 </div>
            );
        }
    }
    
    MyComponent.propTypes = {
        strings: PropTypes.object
    };
    
    MyComponent.defaultProps = {
         strings: {
             someTranslatedText: 'Hello World'
        }
    };
    
    export default translate('MyComponent')(MyComponent);
    

    The Higher Order Component

    On the previous snippet, you might have noticed this on the last line: translate('MyComponent')(MyComponent)

    translate in this case is a Higher Order Component that wraps your component, and provide some extra functionality (this construction replaces the mixins of previous versions of React).

    The first argument is a key that will be used to lookup the translations in the translation file (I used the name of the component here, but it could be anything). The second one (notice that the function is curryed, to allow ES7 decorators) is the Component itself to wrap.

    Here is the code for the translate component:

    import { default as React } from 'react';
    import en from '../i18n/en';
    import fr from '../i18n/fr';
    
    const languages = {
        en,
        fr
    };
    
    export default function translate(key) {
        return Component => {
            class TranslationComponent extends React.Component {
                render() {
                    console.log('current language: ', this.context.currentLanguage);
                    var strings = languages[this.context.currentLanguage][key];
                    return <Component {...this.props} {...this.state} strings={strings} />;
                }
            }
    
            TranslationComponent.contextTypes = {
                currentLanguage: React.PropTypes.string
            };
    
            return TranslationComponent;
        };
    }
    

    It's not magic: it will just read the current language from the context (and that context doesn't bleed all over the code base, just used here in this wrapper), and then get the relevant strings object from loaded files. This piece of logic is quite naïve in this example, could be done the way you want really.

    The important piece is that it takes the current language from the context and convert that into strings, given the key provided.

    At the very top of the hierarchy

    On the root component, you just need to set the current language from your current state. The following example is using Redux as the Flux-like implementation, but it can easily be converted using any other framework/pattern/library.

    import { default as React, PropTypes } from 'react';
    import Menu from '../components/Menu';
    import { connect } from 'react-redux';
    import { changeLanguage } from '../state/lang';
    
    class App extends React.Component {
        render() {
            return (
                <div>
                    <Menu onLanguageChange={this.props.changeLanguage}/>
                    <div className="">
                        {this.props.children}
                    </div>
    
                </div>
    
            );
        }
    
        getChildContext() {
            return {
                currentLanguage: this.props.currentLanguage
            };
        }
    }
    
    App.propTypes = {
        children: PropTypes.object.isRequired,
    };
    
    App.childContextTypes = {
        currentLanguage: PropTypes.string.isRequired
    };
    
    function select(state){
        return {user: state.auth.user, currentLanguage: state.lang.current};
    }
    
    function mapDispatchToProps(dispatch){
        return {
            changeLanguage: (lang) => dispatch(changeLanguage(lang))
        };
    }
    
    export default connect(select, mapDispatchToProps)(App);
    

    And to finish, the translation files:

    Translation Files

    // en.js
    export default {
        MyComponent: {
            someTranslatedText: 'Hello World'
        },
        SomeOtherComponent: {
            foo: 'bar'
        }
    };
    
    // fr.js
    export default {
        MyComponent: {
            someTranslatedText: 'Salut le monde'
        },
        SomeOtherComponent: {
            foo: 'bar mais en français'
        }
    };
    

    What do you guys think?

    I think is solves all the problem I was trying to avoid in my question: the translation logic doesn't bleed all over the source code, it is quite isolated and allows reusing the components without it.

    For example, MyComponent doesn't need to be wrapped by translate() and could be separate, allowing it's reuse by anyone else wishing to provide the strings by their own mean.

    [Edit: 31/03/2016]: I recently worked on a Retrospective Board (for Agile Retrospectives), built with React & Redux, and is multilingual. Since quite a lot of people asked for a real-life example in the comments, here it is:

    You can find the code here: https://github.com/antoinejaussoin/retro-board/tree/master

    0 讨论(0)
提交回复
热议问题