Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Typescript - How to type guard the existence of a module when using dynamic import?

$
0
0

I'm currently using 'react-i18next' and 'i18next-locize-backend') in react native.

I want to use locize differently for each environment(development, production).

For example, in the production environment, I want to use the downloaded translation json file. but in the development environment, I want to receive translation data through backend api on the locize site.

I don't want to download the translation json file in the development environment, but unfortunately, typescript makes a compilation error Cannot find module or its corresponding type declarations.

How can I prevent that compilation error?

The code below is what I wrote.

import i18n, { InitOptions } from 'i18next'import { initReactI18next } from 'react-i18next'import { isProduction } from '../src/utils'import { LOCIZE_PROJECT_ID, LOCIZE_API_KEY } from 'react-native-dotenv'const initOptions: InitOptions = {  compatibilityJSON: 'v3',  debug: false,  lng: 'en',  interpolation: {    escapeValue: false,  },}if (isProduction) {  ;(async function () {    const en = await import('./locales/en-US/translation.json') // where the error occurs.    i18n.use(initReactI18next).init({      ...initOptions,      resources: { en: { translation: en },    })  })()} else {  const backendOptions = {    projectId: LOCIZE_PROJECT_ID,    apiKey: LOCIZE_API_KEY,    referenceLng: 'en',    version: 'latest',  }  import('i18next-locize-backend').then(({ default: LocizeBackend }) => {    i18n      .use(LocizeBackend)      .use(initReactI18next)      .init({ backend: backendOptions, ...initOptions })  })}

tsconfig.json

{"compilerOptions": {"allowJs": true,"allowSyntheticDefaultImports": true,"esModuleInterop": true,"isolatedModules": true,"jsx": "react-native","lib": ["es2017"],"moduleResolution": "node","noEmit": true,"strict": true,"module":"ESNext","target": "esnext","resolveJsonModule": true    },"typeRoots": ["./src/types"],"exclude": ["node_modules","babel.config.js","metro.config.js","jest.config.js"    ]  }

node : 14.17.5.
react native : 0.64.1.
i18next : 21.4.2.
react-i18next : 11.14.1.
typescript : 4.4.4.
i18next-locize-backend : 4.2.3


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>