
Steps to follow while migrating React Project to TypeScript
Suppose you have an existing react project and you recently discovered all the advantages of using TypeScript, and so want to convert your react code into typescript, or maybe your client is demanding to convert an ongoing react project to typescript, we will be discussing all the initial steps to do so in this post.
Installing packages
To convert a react project to TypeScript, first we need to add a few dependencies to our existing project.
npm install —- save typescript @types/node @types/react @types/react-dom @types/jest
Or if you are using yarn
yarn add typescript @types/node @types/react @types/react-dom @types/jest
Here, we are installing a typescript package along with the necessary type files too.
Notice we haven’t changed anything to TypeScript yet. If we run the command to start the project locally (yarn start in my case), nothing should break and the code should run fine. If that’s the case, then great! We’re ready for the next step.
Add tsconfig.json file
Before we can take advantage of TypeScript, we need to configure this via the tsconfig.json. The simplest way for us to get started is to scaffold one using this command:
npx tsc --init
Now we need to configure our tsconfig.json file as follows.
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"noImplicitAny": true,
"module": "ESNext",
"moduleResolution": "Node",
"outDir": "build",
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": false,
"strict": true,
"target": "ES5",
"lib": [
"ESNext",
"DOM",
"DOM.Iterable"
],
"paths": {
"src/*": [
"./src/*"
],
"lib/*": [
"./lib/*"
]
}
},
"include": [
"src/**/*",
"lib/**/*"
]
}
Now, let's start converting .js files to a .tsx /.ts file one by one, and to begin with, we will first convert our index.js file.
Convert the code of your index.js file to typescript and also change its extension to .tsx
Now start your server and load your application in your localhost ✨
Troubleshooting
Sometimes after starting your server, you might come across the following errors.
- You might run into an issue saying could not resolve../../../index.js …
You simply need to change the entry point in webpack.config file from index.js to index.tsx as done below.
entry: {
'repo-name': [path.join(PATHS.SOURCE, 'index.tsx')],
},
2. You might also run into an issue saying you need an appropriate loader to handle this file.
For this issue, add .ts and .tsx extensions along with .js in your rules, in webpack.config file as shown below
rules: [
{
test: /\.js|\.ts|\.tsx$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
} ...
Now you can convert all your React projects to TypeScript. In case of any more queries, you can definitely browser TypeScript official documentation.