How to set up a Node and TypeScript project with Vitest
Set up a Node and TypeScript project: initialize npm, install TypeScript and Vitest, configure tsconfig in strict mode, write a typed function and a test, and run with Vitest.
What this stack gives you
TypeScript adds static types to JavaScript, catching errors before runtime. Node.js runs the code. Vitest is a fast, modern test runner with a Jest-compatible API and first-class TypeScript and ESM support. Together they give a quick, type-safe development loop.
Prerequisites
- Node.js 18 or later
- A terminal
Steps
1. Initialize the project
mkdir stringutils && cd stringutils
npm init -y
2. Install TypeScript and Vitest
npm install -D typescript vitest
3. Configure the TypeScript compiler
Create tsconfig.json with sensible strict settings.
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true
}
}
4. Write code to test
// src/slug.ts
export function slugify(input: string): string {
return input.trim().toLowerCase().replace(/\s+/g, "-");
}
5. Write a Vitest test
Vitest discovers files ending in .test.ts.
// src/slug.test.ts
import { describe, it, expect } from "vitest";
import { slugify } from "./slug";
describe("slugify", () => {
it("lowercases and hyphenates", () => {
expect(slugify("Hello World")).toBe("hello-world");
});
});
6. Run tests and watch mode
Add scripts to package.json and run them.
{ "scripts": { "test": "vitest run", "test:watch": "vitest" } }
npm test
Verification
Run npm test and confirm the test passes. Change the expected string to a wrong value and confirm Vitest reports the diff, then fix it. Run npm run test:watch and confirm it reruns on save.
Next Steps
Add coverage with vitest run --coverage, set up ESLint and Prettier, add type checking with tsc --noEmit, and run tests in continuous integration.
Prerequisites
- Node.js 18+ installed
- Basic command line familiarity
Steps
- 1Initialize the project
- 2Install TypeScript and Vitest
- 3Configure the TypeScript compiler
- 4Write code to test
- 5Write a Vitest test
- 6Run tests and watch mode