Skip to content

Instantly share code, notes, and snippets.

@DominikStyp
Last active June 10, 2022 10:47
Show Gist options
  • Save DominikStyp/c4a8cd4d44278ce61969e9d47439f576 to your computer and use it in GitHub Desktop.
Save DominikStyp/c4a8cd4d44278ce61969e9d47439f576 to your computer and use it in GitHub Desktop.
React + TS: How to introduce TypeScript to old React project

Steps

  • add tsconfig.json and remove jsconfig.json
  • change index.js to index.tsx
  • install dependencies: yarn add typescript @types/node @types/react @types/react-dom @types/jest --dev
  • make test component like Test.tsx and check if typescript works there

Troubleshooting

Problem with relative paths

If your project uses relative-to-root instead of relative-to-current-file paths like below:

import routes from 'domain/routes';

You should add this to the tsconfig.json: "baseUrl": "./src", Then in all the descendant directories you can use paths like tools/something instead of ../../../tools/something

{
"compilerOptions": {
"module": "esnext",
"target": "es5",
"allowJs": true,
"checkJs": false,
"jsx": "react-jsx",
"outDir": "./build",
"rootDir": "./src",
"baseUrl": "./src",
"removeComments": true,
"noEmit": true,
"pretty": true,
"skipLibCheck": true,
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"resolveJsonModule": true,
"isolatedModules": true
},
"include": [
"./src/**/*"
],
"exclude": [
"node_modules"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment