How to add TypeScript into an existing Create-React-App & Use Absolute Path

When I first started React, I used CREATE_REACT_APP, then I would like to add TypeScript but it was very tricky, hopefully this helps! During configuration I had an issue to import tsx files so I have to create a tsconfig.json

  1. npm install –save typescript @types/node @types/react @types/react-dom @types/jest
  1. Create tsconfig.json by yarn tsc –init, add this line “extends”: “./tsconfig.paths.json”

{
 "include": ["src"],
 "extends": "./tsconfig.paths.json", // Add this line
 "compilerOptions": {
   "allowImportingTsExtensions": true,
   "noEmit": true,
   "target": "es2016",
   "jsx": "react",  // change this to react                          
   "module": "commonjs",                              
   "esModuleInterop": true,                           
   "forceConsistentCasingInFileNames": true,          
   "strict": true,                   
   "skipLibCheck": true,                                
 }
}

3. Create tsconfig.paths.json file, add these lines. In the “paths”, you can add whatever path you need for your app, here are some paths that I create for my app, so you don’t need to add of them

{
   "compilerOptions": {
     "baseUrl": ".",
     "paths": {
       "@root/*": ["src/*"],
       "@asset/*": ["src/asset/*"],
       "@components/*": ["src/components/*"],
     }
  }
}

4. Install craco npm i @craco/craco 

5. Create craco.config.js file and add these lines

const path = require("path");


module.exports = {
 webpack: {
   alias: {
     "@root": path.resolve(__dirname, "src/"),
     "@asset": path.resolve(__dirname, "src/asset"),
     "@components": path.resolve(__dirname, "src/components"),
   }
 }
}

6. Go to package.json file, change the scripts to these

 "scripts": {
   "start": "craco start",
   "build": "craco build",
   "test": "craco test",
   "eject": "craco eject"
 }

7. Start the app “npm start

Published by

Leave a comment