Vite doesn't support type-checking while developing your application. In this chapter we'll see how to create a React / TypeScript project using Vite 4.x and how to enable type-checking in both, "Vite Serve" and "Vite Build".
This is a step-by-step tutorial so you can try to reproduce it on your machine.
The only requirement is the latest LTS version of Node or, at least, it should be greater than 16.0.0
.
First create a new React project with Vite:
npm create vite@latest
Set a project name (i.e. react-vitest
), select React
-> TypeScript
.
cd react-vitest # project folder
npm i # install all deps
Open the project in your favorite editor and open the file main.tsx
.
Add the following (wrong) code that should generated a compiler error, since we're assigning a string
to a number
:
src/main.tsx
// ...
const value: number = 'abc'; // <==
// ...
Run the project:
npm run dev
We don't get any error!! 😱
Honestly I would like enable type-checking while I'm developing ( while using "Vite Serve" ):
ViteJS uses ESBuild to compile your code while developing since it's super fast but it doesn't support type checking.
There are several ways to type-check your code:
tsc
in a completely new terminalnpm run build
(yes, type-checking works at build time!)npm i vite-plugin-checker -D
Now update vite.config.ts
to enable the plugin:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import checker from 'vite-plugin-checker';
export default defineConfig({
plugins: [
react(),
checker({ typescript: true }),
],
})
Now, if we re-run the project with npm run dev
we'll get some errors, and of course this is our goal since a string
cannot be a number
Don't forget to remove the code you have added in main.tsx
or you'll always receive some errors
In the next chapter you'll configure Vitest to run your first test!