Vite with TypeScript
In this page:
npm create vite@latest project-name -- --template vanilla-ts
Core Concept
Vite is a dev server and bundler that serves your source files over native ES modules during development (skipping a full bundle step entirely) and switches to Rollup for a production build, with TypeScript support built in out of the box.
Example: Core Concept
// Vite serves native ES modules in dev, bundles with Rollup for production
console.log("Vite supports TypeScript out of the box, no config needed");
Basic Setup
Scaffolding with npm create vite@latest -- --template vanilla-ts (or react-ts, vue-ts, etc.) generates a working tsconfig.json and dev server with zero extra configuration needed to start writing typed code.
Example: Basic Setup
// npm create vite@latest my-app -- --template vanilla-ts
console.log("Scaffolds a working tsconfig.json and dev server instantly");
Typed Example
Vite transpiles TypeScript file-by-file via esbuild for speed but doesn't type-check during the dev server — running vue-tsc/tsc --noEmit alongside vite build is what actually catches type errors.
Example: Typed Example
// Vite transpiles via esbuild but doesn't type-check during dev
// vue-tsc / tsc --noEmit catches real type errors
console.log("Vite's dev server is fast because it skips type checking");
Project Usage
In a real project, Vite's instant hot-module-replacement means editing a typed component reflects in the browser almost immediately, since only the changed module is re-transpiled rather than the whole bundle.
Example: Project Usage
// Editing a .ts file triggers instant HMR for just that module
console.log("Vite's HMR only re-transpiles the changed module");
Best Practices
Keep type-checking as a separate step (a tsc --noEmit script run in CI or a pre-commit hook) since Vite's own dev/build pipeline intentionally skips it for speed and won't catch type errors on its own.
Example: Best Practices
// package.json: "build": "tsc --noEmit && vite build"
console.log("Run tsc --noEmit as a separate type-checking step");
- Assuming
vitetype-checks during dev, when it only strips types with esbuild, so errors appear only when you runtsc. - Using
const enumornamespacefeatures that need full type information, which esbuild does not support well. - Forgetting
isolatedModulesand type-onlyimport type, causing re-exported types to fail.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: