How to setup React-Native with Yarn and Typescript

4.4k views Asked by At

So up until now I have been working on my project using barebone react-native and npm and its was going okay but now I face a problem

I need to add a new feature at the later stages which would be a headache and therefore I decided to restart the build as I could fix many of bad codings and errors.

Now this do over is going to be a different setup I am not going to use npm, insted I want to use yarn. I am not going to use React-Native alone, I am going to use it with typescript!

Now here is the problem I have installed yarn on windows laptop using the installer but am not entirely sure how to create react-native app and on top of that add typescript. Looking through the docs and other forums the answer keeps changing on how to create react-native app or how to setup typescript with that. So please tell me

How Do I set up a react-native app using yarn with typescript on a windows laptop?

2

There are 2 answers

2
programandoconro On BEST ANSWER

This is what worked for me:

Create your react-native App:

npx react-native init MyApp
cd MyApp

Add typescript:

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

Then create a tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

And a jest.config.js

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

Change your App.js to App.tsx.

That is it. Now you can change the configuration file with more strict type rules if you want to.

All the documentation is in https://reactnative.dev/docs/typescript.

Side Note: npx react-native init MyApp --template react-native-template-typescript resulted in errors when building the App. That is why I tried using the above method.

1
Kingsley On

I think you have probably installed $ apt install yarn Instead use $ sudo npm install --global yarn.

Then try to install your app again with npx command:

npx react-native init MyApp --template react-native-template-typescript