How to lazy load js file in React (for multilingual application)

I would like to create a multilingual application with React.

As I see it, this will have a js file for each language, for example:

en.js:

module.exports = {
    langEnglish: 'English',
    langFrench: 'French',

    navHome: 'Home',
    navUsers: 'Users',
    ...
};

fr.js:

module.exports = {
    langEnglish: 'Anglais',
    langFrench: 'FranΓ§ais',

    navHome: 'Accueil',
    navUsers: 'Utilisateurs',
    ...
};

Since each language file will be quite large and dozens of different languages ​​can be supported, I would prefer to download only the correct file for use depending on the selected language, in order to minimize download time (and bandwidth usage).

For example, I could have a variable in application state

var App = React.createClass({
    getInitialState: function () {
        return {
            lang: 'en'
        };
    },

    ...

and some user control to switch this variable between frand en.

en.js , , fr.js .. ?

+4
1

webpack, . webpacks require.ensure .

:

i18n.js

var currentTranslation = {};

module.exports = {
    getTranslation: function() {
        return currentTranslation;
    },

    loadI18n: function(region, cb) {
        switch (region) {
            case 'en':
                require.ensure([], function(require) {
                    cb(currentTranslation = require('./en'));
                }, 'i18n-en'); // will create a chunk named 'i18n-en'
                break;
            case 'fr':
                require.ensure([], function(require) {
                    cb(currentTranslation = require('./fr'));
                }, 'i18n-fr'); // will create a chunk named 'i18n-fr'
                break;
            default:
                require.ensure([], function(require) {
                    cb(currentTranslation = require('./en'));
                }, 'i18n-en');
        }
    }
}

App.js

var i18n = require('./i18n');

async

:

i18n.loadI18n('en', function(texts) {
    console.log(texts);
});

webpack , ,

var texts = i18n.getTranslation(); // call this from anywhere and it will return english texts

,

i18n.loadI18n('fr', function(texts) {
    console.log(texts);
});

var texts = i18n.getTranslation(); // will return french texts
+4

Source: https://habr.com/ru/post/1661665/


All Articles