DoneDeal0
DoneDeal0

Reputation: 6257

How to import i18next in React Native?

I'm trying to use react-i18next in a React Native app. When importing i18next at the top of my index.js or app.tsx file, the build crashes with this error:

ERROR TypeError: undefined is not a function, js engine: hermes ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes

Here is the code:

index.js:

import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";
import "i18n/index";

AppRegistry.registerComponent(appName, () => App);

i18/index.ts:

import i18n, { LanguageDetectorAsyncModule } from "i18next";
import { initReactI18next } from "react-i18next";
import { Platform, NativeModules } from "react-native";
import { AsyncStorage } from "react-native";
import en from "./en.json";
import fr from "./fr.json";

const languages = {
  EN: "en",
  FR: "fr",
};

const resources = {
  en: { translation: en },
  fr: { translation: fr },
};

const detectLocale = () => {
  const storedLocale = AsyncStorage.getItem("locale");
  if (storedLocale) {
    return storedLocale;
  }
  const mobileLocale =
    Platform.OS === "ios"
      ? NativeModules.SettingsManager.settings.AppleLocale ||
        NativeModules.SettingsManager.settings.AppleLanguages[0]
      : NativeModules.I18nManager.localeIdentifier;
  if (mobileLocale) {
    return mobileLocale;
  }
  return languages.EN;
};

const LanguageDetector = {
  type: "languageDetector" as LanguageDetectorAsyncModule["type"],
  async: false,
  init: () => {},
  detect: detectLocale,
  cacheUserLanguage: () => {},
};

export default i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources,
    fallbackLng: languages.EN,
    keySeparator: ".",
    whitelist: [languages.EN, languages.FR],
    interpolation: { escapeValue: false },
  });

How to fix this?

Upvotes: 0

Views: 623

Answers (1)

Daniel Sirakov
Daniel Sirakov

Reputation: 112

Try rerunning metro bundler and make sure there isn't another metro bundler running for another react native application.

Upvotes: 0

Related Questions