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
anddevDependencies
from thepackage.json
file in your old app to your new app'spackage.json
file and runnpm install
to install them.Copy your
App.jsx
andmain.jsx
files to your new app and change the extension to.tsx
In
main.tsx
addas HTMLElement
afterdocument.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
andmain.jsx
to.tsx
In
main.tsx
addas HTMLElement
afterdocument.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 changemain.jsx
tomain.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
Top comments (5)
Thank you ! This is the most concise migration guide I found !
You're welcome :)
i followed second method and i get given beleow error what should i do please help me
How about if I want the typescript go back to javascript? is it possbile?
You can try doing the reverse for each step (e.g.
tsx
extension tojsx
), but your main problem will be modifying your files and removing all the type definitions.Also, There's no reason for wanting to go back to JavaScript :)