255 words
1 minute
Why Vite? (And How to Set It Up)

Why Vite?#

Forget Create React App. Vite is the answer.

Vite vs CRA - No Contest#

FeatureViteCreate React App
Dev Server Start~300ms~30+ seconds
Hot ReloadInstant1-3 seconds
Build TimeFastSlow
Bundle SizeSmallerLarger
Modern JSNativePolyfills

Quick Start#

React + TypeScript#

Terminal window
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev

Vue#

Terminal window
npm create vite@latest my-app -- --template vue

Vanilla#

Terminal window
npm create vite@latest my-app -- --template vanilla

Project Structure#

my-app/
├── public/
│ └── favicon.ico
├── src/
│ ├── components/
│ ├── App.tsx
│ ├── main.tsx
│ └── index.css
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.ts

My Vite Config#

vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
server: {
port: 3000,
open: true,
},
build: {
outDir: 'dist',
sourcemap: true,
},
});

Path Aliases (Game Changer)#

vite.config.ts
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@utils': path.resolve(__dirname, './src/utils'),
},
}

Now you can do:

import Button from '@components/Button';
import { formatDate } from '@utils/date';

Instead of:

import Button from '../../../components/Button';
// gross

Environment Variables#

.env
VITE_API_URL=https://api.example.com
VITE_APP_NAME=My App
// Use it like this
const apiUrl = import.meta.env.VITE_API_URL;

Adding Tailwind#

Terminal window
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
index.css
@tailwind base;
@tailwind components;
@tailwind utilities;

Why Is Vite So Fast?#

  1. Native ESM — No bundling in dev mode
  2. esbuild — 10-100x faster than webpack
  3. Hot Module Replacement — Only updates what changed
  4. On-demand compilation — Only compiles what you need

Commands#

Terminal window
# Development
npm run dev
# Build for production
npm run build
# Preview production build
npm run preview

Once you go Vite, you never go back!

Seriously, try it. You’ll thank me later.

Why Vite? (And How to Set It Up)
https://blog.lukkid.dev/posts/why-vite/
Author
LUKKID
Published at
2024-04-20
License
CC BY-NC-SA 4.0