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

查看:96
本文介绍了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 这将允许此功能,因此您可以按顺序使用填充使用它。

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;

但是,现在这将基于承诺,因此需要像这样调用:

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天全站免登陆