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
dependenciesanddevDependenciesfrom thepackage.jsonfile in your old app to your new app'spackage.jsonfile and runnpm installto install them.Copy your
App.jsxandmain.jsxfiles to your new app and change the extension to.tsxIn
main.tsxaddas HTMLElementafterdocument.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
.jsxto.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.jsxandmain.jsxto.tsxIn
main.tsxaddas HTMLElementafterdocument.getElementById('root')
...
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
...
In the
index.htmlfile, find the line<script type="module" src="/src/main.jsx"></script>and changemain.jsxtomain.tsxInstall 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.jsfile from.jsto.tsChange the extension of your components from
.jsxto.tsxand 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 :)
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.
tsxextension 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 :)
i followed second method and i get given beleow error what should i do please help me
