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

纵饮孤独 提交于 2019-12-05 18:33:25

Make use of some advanced webpack features, such as code splitting. You can use webpacks require.ensure for async loading your files.

Create a file:

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');

and when you need the translation strings to be loaded async

you can call:

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

once webpack loads that chunk, you will be able to get the translation texts using the function

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

if you want to switch language, just call

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

var texts = i18n.getTranslation(); // will return french texts
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!