I have an 'external' intl provider because I have to handle some labels outside react components. I am trying to dynamically load the locales without using require statements and I am having a issue I am not sure why it's happening. So, the following code works:
//intlProvider.js
import { IntlProvider, addLocaleData } from 'react-intl';
import Locale from '../../../../utils/locale';
const locale = Locale.getLocale();
addLocaleData(require(`react-intl/locale-data/${locale}`));
const messages = Locale.getMessages('prot');
const intlProvider = new IntlProvider({ locale, messages });
const { intl } = intlProvider.getChildContext();
export default intl;
then I read the intl in a sharedMessages.js file:
import { defineMessages } from 'react-intl';
import intl from '../components/i18n/Intl';
const messages = defineMessages({
interest: {
id: 'sharedMessages.rate.label',
defaultMessage: 'Interest',
},
bank: {
id: 'sharedMessages.bank.label',
defaultMessage: 'Bank',
},
});
function prepareSharedMessages() {
const msgsObj = {};
Object.keys(messages).forEach(item => {
msgsObj[item] = intl.formatMessage(messages[item]);
});
return msgsObj;
}
const sharedMessages = prepareSharedMessages();
export default sharedMessages;
The above code works fine, but since I want to get rid of the require statement in this line (as dynamic imports increase the bundle a lot):
addLocaleData(require(`react-intl/locale-data/${locale}`));
I tryed to replace it for:
(async localeCode => {
const localeData = await import(`react-intl/locale-data/${localeCode}`);
addLocaleData(localeData.default);
})(locale);
Expected behavior I'd expect the locale to be loaded properly, but apparently the application is trying to get it before it should. Since I am using async/await, I'd expect it to be set before the rest of the application tries to use it. (If it was inside react components, I could use componentDidMount to trigger the locale, but how can I achieve this behavior for non react components?)
Current behavior After replacing the require for the import statement above mentioned, I am getting the react-intl warning:
[React Intl] Missing locale data for locale: "de". Using default locale: "en" as fallback.
My Environment:
- react-intl 2.7.0
- react 16.0.0
- node 9.10.0
OS: macOS Mojave 10.14
Browser Version: Chrome 71.0.3578.98 (Official Build) (64-bit)