How to setup Vite.js + React.js + TypeScript + Vitest.js

Zamin Mirzad
6 min readFeb 17, 2023

--

In this blog article, I’ll walk you through setting up a dev environment with ViteJS, ReactJS, TypeScript, ViTest, Prettier, and ESLint. You can write code that is neat, tested, and manageable with the aid of this setup.

First, let’s have a short introduction to the tools we use

This setup includes

  1. Eslint, eslint — airbnb — config, prettier
  2. vitest, jsdom, @testing-library
  3. react-router

LET’S GET STARTED

Run the following commands to create a project directory of your desired name

yarn create vite

The above command will ask you for the project name, framework, and variant. in our case will be vite-react-ts, React and TypeScript respectively.

yarn create vite

Next, go to the project directory and run the command yarn to install the dependencies, and finally yarn dev to run it in the localhost server. The result will be something like this

yarn dev
package.json

EsLint: time to configure Eslint

Along with the following setup install the Eslint vs-code extension to work with these configs

yarn add -D eslint
npx eslint --init // this command initialize eslint's CLI

After running the above commands the Eslint CLI will ask some questions regarding your configs, use the arrow and enter keys to make a selection.

                                                                  // Anwers⤵
✔ How would you like to use ESLint? · problems // To check syntax and find problems
✔ What type of modules does your project use? · esm // JavaScript modules (import/export)
✔ Which framework does your project use? · react // React
✔ Does your project use TypeScript? · No / Yes // Yes
✔ Where does your code run? · browser // Browser
✔ What format do you want your config file to be in? · JavaScript // JavaScript
✔ Would you like to install them now? » No / Yes // Yes
✔ Which package manager do you want to use? · yarn // Yarn

This’ll install some dependencies and create the file .eslintrc.cjs which contains the Eslint configs. re-start your vs-code and it may show some errors or warnings

‘React’ must be in scope when using JSXeslintreact/react-in-jsx-scope

Now let’s install airbnb-style-guide by running the following commands which require these extra related dependencies eslint-plugin-import, eslint-plugin-react, eslint-plugin-react-hooks, and eslint-plugin-jsx-a11y.

npx install-peerdeps -D eslint-config-airbnb 

Say yes if you’re using yarn and the eslint-config-airbnb will be installed with its related dependencies.

Now open .eslintrc.cjs file and add the following:

...   
"extends": [
"eslint:recommended", // Remove the default eslint recommendations
"airbnb", // Add this line
"airbnb/hooks", // Add this line
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended"
],
...

As you add these two lines and save, vs-code will start showing errors and complaining about indentations or something else.

errors related to indentation

To fix them either click the blue light bulb or Ctrl+shift+p > Eslint: Fix all auto-fixable problems

eslint fix

Eslint TypeScript Support

let’s add support for TypeScript as well since we use it in our project. Install eslint-config-airbnb-typescript and then make the following changes in the .eslintrc.cjs.

  yarn add -D eslint-config-airbnb-typescript
{
...,
extends: [
'airbnb',
'airbnb/hooks',
'airbnb-typescript', // Add this line
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
],
...,
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: './tsconfig.json', // Add this line as well
},
...
}

Now it may show a parser error for .eslintrc.cjs saying Eslint was configured to run in parserOptions.project but tsconfig.json does not include this file. Meaning we should tell tsconfig.json to follow .eslintrc.cjs to do it make the following changes in tsconfig.json and then reload vs-code:

{
"include": [
"src",
".eslintrc.cjs", // add this line
],
}

After reloading that error should disappear. now you’ll see eslint errors on all files that don’t match the rules so, run the auto-fixable command and fix them.

Prettier: now let’s configure prettier

Run the following command to install prettier and other config dependencies as a devDepenency. and don’t forget to install the prettier’s vs-code extension as well.

yarn add -D prettier eslint-config-prettier eslint-plugin-prettier 

Add a new file .prettierrc.cjs to the root of the application with the following content:

module.exports = {
trailingComma: 'es5',
tabWidth: 2,
semi: true,
singleQuote: true,
};

Now if you set your vs-code’s default format to use prettier it will format your code using the above settings.

Note: there are files that we don’t need to format like node_modules, build directory, and … then we should exclude them by creating a .prettierignore file at the root of the application and put your configs:

# Ignore artifacts:
build
coverage
node_modules*

# Ignore all HTML files:
*.html

and add bellow script in package.json to do formatting for all files at once

{
...
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"prettier": "prettier --write ." // add this script
},
...
}

Vitest: time to set up testing libraries in our case vitest.dev

Vitest is a test runner from vite.js that works with other testing libraries like testing-library/react, jsdom, and others. Install as devDependency with:

yarn add -D vitest
yarn add -D @testing-library/react @testing-library/jest-dom

There are multiple setups here we go with this config in vite.config.ts

/* eslint-disable import/no-extraneous-dependencies */
/// <reference types="vitest" />
/// <reference types="vite/client" />

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: 'jsdom',
setupFiles: ['./src/setupTest .ts'],
},
});

now create the setupTests.ts in the src directory with the following content:

/* eslint-disable import/no-extraneous-dependencies */
import matchers from '@testing-library/jest-dom/matchers';
import { expect } from 'vitest';

expect.extend(matchers);

Now let’s create a test demo App.test.tsx with the content:

/* eslint-disable linebreak-style */
import { describe, it } from 'vitest';
import { screen, render } from '@testing-library/react';
import App from './App';

describe('App', () => {
it('should render hello world', () => {
// Arrange
render(<App />);
const heading = 'Hello world!';
// Act
// Expect
expect(
screen.getByRole('heading', {
level: 1,
})
).toHaveTextContent(heading);
});
});

Now add a ‘test’ script to package.json with the value ‘vitest’ and run yarn test

yarn test

React-Router-Dom

Routing is a vital feature of every website and so for React. Let’s now configure our setup and testing to work with routing as well.

First install it

yarn add react-router-dom

Now create a directory called pages and a file Home.tsx which contain your website’s home page along with Home.test.tsx for test with the following basic contents.

// Home.tsx
export default function Home() {
return (
<div>
<h1>Home</h1>
</div>
);
}
// Home.test.tsx
import { describe, it } from 'vitest';
import { screen, render } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import Home from './Home';

describe('App', () => {
it('should render hello world', () => {
// Arrange
render(<Home />, { wrapper: BrowserRouter });
const text = 'Home';
// Act
// Expect
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(text);
});
});

Now wrap the App.tsx with BrowserRouter, Routes and the corresponding Route for Home.tsx

// App.tsx 
// and App.test.tsx is no longer needed you can delete

import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';

export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</BrowserRouter>
);
}

Now if you run the yarn test command the test should pass successfully.

That’s it guys for this setup. if I missed something or did the wrong way please leave a comment or contact. Thanks

If you loved this, then don’t forget to like, follow, save and share with friends

Let’s grow together ❤️🤝👨‍💻

--

--

Zamin Mirzad

I'm Software Developer and I'm dedicated to continuous learning and excited to share my insights and experiences on Medium. Let's learn together