Conditional import or alternative in JavaScript (ReactJS WebApp)?(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)中的条件导入或替代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript(ReactJS WebApp)中的条件导入或替代?
基础教程推荐
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
