Adding TypeScript to existing create-react-app app
If you want to add TypeScript to the existing react app use below command
npm install --save-dev typescript @types/node @types/react @types/react-dom @types/jest
Rename at least one file from js/jsx
to .ts/tsx
. For example, rename index.js
to index.ts
or index.tsx
and then start the server. This will generate the tsconfig.json
file automatically and you are ready to write React in TypeScript.
As of react-scripts 2.10 you can add TypeScript to an existing project or when creating a new project.
existing project
yarn add typescript @types/node @types/react @types/react-dom @types/jest --dev
...then rename your .js
files to .tsx
new project
yarn create react-app my-app --template typescript
You can read more here.
There is a recent pull request adding Typescript. It's not merged yet.
Also, the next major version of CRA will upgrade to Babel 7, which supports Typescript.
So I'd suggest you to wait a few weeks. It should be really easy then to add TS to any CRA project.
You can add typescript to an existing project using one of the following commands:
To add TypeScript to an existing Create React App project, first install it:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
or
yarn add typescript @types/node @types/react @types/react-dom @types/jest
You can read more here
But the problem is when you are changing a file except index.js like App.js
to App.tsx
it gives you an error that module not found error can't resolve './App' . The source of this issue is lacking a tsconfig.json file. So by creating one the error would be removed. I recommend using the below tsconfig:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"],
"exclude": [
"node_modules"
]
}