TypeScript – How to add TS to existing React Native app?

Installation

Install packages

yarn add typescript @types/jest @types/react @types/react-native @types/react-test-renderer

Create “tsconfig.json” file

{
    "compilerOptions": {
      "allowJs": true,
      "allowSyntheticDefaultImports": true,
      "esModuleInterop": true,
      "isolatedModules": true,
      "jsx": "react",
      "lib": ["es6"],
      "moduleResolution": "node",
      "noEmit": true,
      "strict": true,
      "target": "esnext",
      "resolveJsonModule": true // React Native template app is using import JSON file directly
    },
    "exclude": [
      "node_modules",
      "babel.config.js",
      "metro.config.js",
      "jest.config.js"
    ]
  }

Create jest.config.js file

module.exports = {
  preset: 'react-native',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};

Fix error when changing “.js” to “.tsx”

Could not find a declaration file for module ‘react-redux’

yarn add @types/react-redux --dev

Dynamic imports are only supported when the ‘–module’ flag is set to ‘es2020’, ‘esnext’, ‘commonjs’, ‘amd’, ‘system’, or ‘umd’.

Add the following option into “tsconfig.json” file

...
"compilerOptions": {
        ...
        "module": "esnext"
}

Be the first to comment

Leave a Reply

Your email address will not be published.


*