我有一个支持30+语言的小应用程序。我使用react-intl来完成我的任务。在react-intl中,我必须导入每个本地文件大小约为7-8KB的所有语言环境,而我希望减少这些不必要的导入,并且只想导入一个文件
app.js
import {IntlProvider, addLocaleData} from 'react-intl'
import ca from 'react-intl/locale-data/ca'
import cs from 'react-intl/locale-data/cs'
...
import hu from 'react-intl/locale-data/hu'
import id from 'react-intl/locale-data/id'
import enMessages from '../assets/translations/en.json'
Translations.getLocale('fr').then(function(localeData){
addLocaleData(localeData);
console.log("localeData");
console.log(localeData); //Code instead of array of objects
}, function(status) {
alert('Something went wrong.');
});现在,ca、cs、hu等包含从各自的js文件返回的array of objects。
我尝试使用XHR,但返回的不是对象数组,而是.js文件中编写的代码。有没有什么方法可以动态导入js文件,或者是否可以从XMLHttpRequest返回的代码中获取对象数组。
Translations.js
getLocale: function(lang, successHandler, errorHandler){
var url = 'http://localhost/img/' + lang + '.js';
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
//xhr.responseType = 'application/javascript';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
//return message;
}https://stackoverflow.com/questions/38239600
复制相似问题