Add TypeScript to Existing Vite Project
Recently, I added TypeScript to my personal project, Payday Calendar Generator, a React project using Vite as the bundler. Here's what I learned:
Initial Project Changes
These steps only work for existing React projects using Vite. Conveniently, it's a handful of steps since Vite supports TypeScript really well.
NOTE: This tutorial will utilize the official Vite + React + TS StackBlitz for files and references.
Update configuration files
- Create TypeScript config files (
tsconfig.json
andtsconfig.node.json
) in project root- Copy the respective config content from the StackBlitz example
- Refactor Vite config file from
vite.config.js
tovite.config.ts
- Create a
src/vite-env.d.ts
- Copy the respective config content from the StackBlitz example
- Modify
package.json
'snpm run build script
- Update from
"build": "vite build",
to"build": "tsc && vite build",
- Update from
Update entry point
- Refactor
main.jsx
tomain.tsx
- Update
index.html
to includemain.tsx
NOTE: At this point, the Vite project should be ready for TypeScript compilation, but as always, test the project to see if anything is not configured correctly. Here's some additional task I had to do.
Additional tasks
- Update
.js
/.jsx
filename globs to include.ts
/.tsx
where necessary- Like
tailwind.config.js
- Like
Start Migration
Now the fun starts! My strategy was to update each file (and associated test file) to TypeScript one at a time. This flow was my guide for each file.
- Rename file from
.js
/.jsx
to.ts
/.tsx
- Convert CommonJS modules to ES6 modules
- Add types!
Conclusion
Vite is a blazing-fast bundler, and adding TypeScript to a Vite project will make development even more pleasant.