JavaScript(ReactJS WebApp)中的条件导入或替代? [英] Conditional import or alternative in JavaScript (ReactJS WebApp)?

查看:37
本文介绍了JavaScript(ReactJS WebApp)中的条件导入或替代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 ReactJS webapp 实现国际化.如何避免加载所有语言文件?

I'm implementing internationalization for a ReactJS webapp. How can I avoid loading all language files?

import ru from './ru';
import en from './en';

// next lines are not important for this question from here
import locale from 'locale';
const supported = new locale.Locales(["en", "ru"])

let language = 'ru';

const acceptableLanguages = {
    ru: ru,
    en: en,
}
if (typeof window !== 'undefined') {
    const browserLanguage = window.navigator.userLanguage || window.navigator.language;
    const locales = new locale.Locales(browserLanguage)
    language = locales.best(supported).code
}

// till here

// and here i'm returning a static object, containing all language variables
const chooseLang = () => {
    return acceptableLanguages[language];
}
const lang = chooseLang();

export default lang;

推荐答案

不幸的是,在 ES6 中没有办法动态加载模块.

Unfortunately there is no way to dynamically load modules in ES6.

即将推出的 HTML Loader Spec 将支持此功能,因此您可以使用 一个 polyfill 以便使用它.

There is an upcoming HTML Loader Spec which will allow for this functionality, so you could use a polyfill in order to use that.

const chooseLang = () => System.import(`./${language}`);
export default chooseLang;

但是,这现在是基于 Promise 的,因此需要像这样调用它:

However, this would now be promise-based so it would need to be called like so:

import language from "./language";
language.chooseLang().then(l => {
    console.log(l);
});

但请记住,该规范可能会彻底改变(或完全放弃).

But bear in mind, that spec could change radically (or be dropped altogether).

另一种选择是不将本地化存储为 Javascript 模块,而是存储为 JSON,例如

Another alternative would be to not store your localizations as Javascript modules, but as JSON instead, e.g.

en.json

{ "hello_string": "Hi!" }

language.js

const chooseLang = () => {
    return fetch(`./${language}.json`)
        .then(response => response.json());
};

同样,这将是基于承诺的,因此需要这样访问:

Again, this would be promise based so would need to be accessed as such:

import language from "./language";
language.chooseLang().then(l => {
    console.log(l.hello_string);
});

该解决方案将完全符合 ES6 标准,并且不依赖于未来可能的功能.

That solution would be fully ES6-compliant and would not rely on possible future features.

这篇关于JavaScript(ReactJS WebApp)中的条件导入或替代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆