Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@doodle/i18n / src / import.js
Size: Mime:
import { normalizeLocale } from './utils';

/**
 * Dynamic import of a translation file, typically a JSON file
 * You have to define an alias (`resolve.alias`) in your webpack configuration
 * i.e.
 * {
 *   resolve: {
 *     alias: {
 *       i18n: path.resolve('./i18n')
 *     }
 *   },
 *   //...
 * },
 * @param {String} locale a locale, i.e. `en`
 * @returns {Object} imported module, default export in `default` field
 */
export async function importMessages(locale) {
  try {
    const normalizedLocale = normalizeLocale(locale);
    const importedModule = await import(`i18n/${normalizedLocale}`);
    return importedModule.default;
  } catch (error) {
    // if the requested locale is not present, return an empty object
    return {};
  }
}

/**
 * Dynamic import of `react-intl`'s locale data
 *
 * @see https://github.com/yahoo/react-intl/wiki#locale-data-in-browsers
 * @param {String} locale a locale, i.e. `en`
 * @returns {import('react-intl').LocaleData} locale data object
 */
export async function importLocaleData(locale) {
  const normalizedLocale = normalizeLocale(locale);
  const [language] = normalizedLocale.split('-');
  const importedModule = await import(`react-intl/locale-data/${language}`);

  // react-intl's locale data provides additional specific locales, i.e. `en-GB`: we'll pick the base locale data
  const [specificLocaleData] = importedModule.default.filter(localeData => localeData.locale === normalizedLocale);
  const defaultLocaleData = importedModule.default.filter(localeData => localeData.locale === language);

  return specificLocaleData || defaultLocaleData;
}

/**
 * Dynamic import of the `Intl` polyfill, but only if there is no support
 */
export async function importIntl() {
  if (!global.Intl) {
    await import('intl');
  }
}