Hello React Vitest

React, Vite 4 & TypeScript

Enable Type Checking

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".

2022-12-26
4 min read
Difficulty
react
typescript

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.

Install all dependencies:

cd react-vitest  # project folder
npm i            # install all deps

Add fully-support for TypeScript

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:

ReactTypeScript
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:

  • manual run tsc in a completely new terminal
  • configure your editor to run TypeScript
  • run a build with npm run build (yes, type-checking works at build time!)
  • or, my favorite one: you can install the vite-plugin-checker to enable type checking in both, "Vite Serve" and "Build Mode":
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!

Keep updated about latest content
videos, articles, tips and news
BETA