Migrating a Vite / React app from JavaScript to TypeScript

Migrating a Vite / React app from JavaScript to TypeScript

ยท

2 min read

When you first make a React app with Vite, you have the option to choose either JavaScript or TypeScript as your preferred language. but what if you start your app in JavaScript and midway through, change your mind and want to use TypeScript instead? well in that case you have two options:

1. Make a new TypeScript app and copy everything from your old app to the new one

  • Copy any changes you've made and the lines for any package you've installed under dependencies and devDependencies from the package.json file in your old app to your new app's package.json file and run npm install to install them.

  • Copy your App.jsx and main.jsx files to your new app and change the extension to .tsx

  • In main.tsx add as HTMLElement after document.getElementById('root')

      ...
      ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
      ...
    
  • Copy everything else like utility functions and static resources to the new app

  • Copy all the changes you've made to the config files of any other package you've installed over to the config files in your new project

  • Copy the component files, change the file extension from .jsx to .tsx, and modify them to work with TypeScript

2. Make a new TypeScript app but copy the needed files back to your old app instead

  • Change the extension of your App.jsx and main.jsx to .tsx

  • In main.tsx add as HTMLElement after document.getElementById('root')

      ...
      ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
      ...
    
  • In the index.html file, find the line <script type="module" src="/src/main.jsx"></script> and change main.jsx to main.tsx

  • Install TypeScript packages

      npm install -D typescript @types/react @types/react-dom
    
  • Copy these files from your new app to your old one

      tsconfig.json
      tsconfig.node.json
      src/vite-env.d.ts
    
  • Change the extension of the vite.config.js file from .js to .ts

  • Change the extension of your components from .jsx to .tsx and modify them to work with TypeScript

๐ŸŽ‰ In the end, cross your fingers, run your app, and hope everything works!

Source: Discussion on Vite GitHub

ย