Back to librarydev
Vite
Skill for Vite — auto-generated from documentation
by skynetv1.0.0
vitedevauto-generated
0
Total Uses
0
Successes
0%
Success Rate
Compatible Agents
claude-codecodexgemini
Instruction
---
name: Vite
description: Use when you need to set up modern frontend build tooling, create development servers, bundle applications, or work with Vite-based projects. Essential for fast development workflow with HMR, optimized production builds, and modern JavaScript frameworks.
category: dev
metadata:
author: skynet
version: 1.0.0
---
# Vite Skills
## Project Setup
### Create New Project
```bash
# Vanilla JavaScript
npm create vite@latest my-app -- --template vanilla
# React
npm create vite@latest my-react-app -- --template react
npm create vite@latest my-react-ts-app -- --template react-ts
# Vue
npm create vite@latest my-vue-app -- --template vue
npm create vite@latest my-vue-ts-app -- --template vue-ts
# Other frameworks
npm create vite@latest my-app -- --template svelte
npm create vite@latest my-app -- --template solid
npm create vite@latest my-app -- --template preact
npm create vite@latest my-app -- --template lit
```
### Initialize in Existing Directory
```bash
npm create vite@latest . -- --template react
yarn create vite . --template vue-ts
pnpm create vite . --template svelte
```
## Development Commands
### Start Development Server
```bash
# Standard dev server
npm run dev
yarn dev
pnpm dev
# Custom port and host
npx vite --port 3000
npx vite --host 0.0.0.0 --port 8080
# HTTPS development
npx vite --https
npx vite --https --cert ./path/to/cert.pem --key ./path/to/key.pem
# Debug mode
npx vite --debug
npx vite --force # Force optimizer to ignore cache
```
### Build Commands
```bash
# Production build
npm run build
npx vite build
# Build with custom output directory
npx vite build --outDir dist-custom
# Build and analyze bundle
npx vite build --mode analyze
# Preview production build
npm run preview
npx vite preview --port 4173
```
## Configuration
### Basic vite.config.js
```javascript
import { defineConfig } from 'vite'
import { resolve } from 'path'
export default defineConfig({
// Base URL for assets
base: '/my-app/',
// Build options
build: {
outDir: 'dist',
assetsDir: 'assets',
sourcemap: true,
minify: 'terser',
target: 'es2015'
},
// Dev server options
server: {
port: 3000,
open: true,
cors: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
// Path resolution
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
'@components': resolve(__dirname, 'src/components')
}
}
})
```
### Framework-Specific Configs
#### React Configuration
```javascript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
esbuild: {
loader: 'jsx',
include: /src\/.*\.[tj]sx?$/,
exclude: []
}
})
```
#### Vue Configuration
```javascript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`
}
}
}
})
```
## Environment Management
### Environment Files Setup
```bash
# Create environment files
touch .env.local # Local overrides (ignored by git)
touch .env.development # Development environment
touch .env.production # Production environment
touch .env.staging # Staging environment
```
### Environment Variables
```bash
# .env.development
VITE_API_URL=http://localhost:8080/api
VITE_APP_TITLE=My App (Dev)
VITE_DEBUG=true
# .env.production
VITE_API_URL=https://api.myapp.com
VITE_APP_TITLE=My App
VITE_DEBUG=false
```
### Using Environment Variables
```javascript
// In your code (only VITE_ prefixed vars are exposed)
const apiUrl = import.meta.env.VITE_API_URL
const isDev = import.meta.env.DEV
const isProd = import.meta.env.PROD
const mode = import.meta.env.MODE
// Type definitions (vite-env.d.ts)
interface ImportMetaEnv {
readonly VITE_API_URL: string
readonly VITE_APP_TITLE: string
readonly VITE_DEBUG: string
}
```
## Asset Management
### Static Assets
```javascript
// Import assets
import logo from './assets/logo.png'
import styles from './styles.module.css'
// Dynamic imports
const getImageUrl = (name) => {
return new URL(`./assets/${name}.png`, import.meta.url).href
}
// Public directory assets (served from /public)
// Reference as: /favicon.ico, /images/hero.jpg
```
### CSS and Preprocessing
```javascript
// vite.config.js
export default defineConfig({
css: {
modules: {
localsConvention: 'camelCaseOnly'
},
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/mixins.scss";`
},
less: {
math: 'parens-division'
}
},
postcss: {
plugins: [
require('autoprefixer'),
require('cssnano')
]
}
}
})
```
## Plugin System
### Common Plugins Installation
```bash
# Essential plugins
npm install -D @vitejs/plugin-react
npm install -D @vitejs/plugin-vue
npm install -D @vitejs/plugin-legacy
# Utility plugins
npm install -D vite-plugin-eslint
npm install -D vite-plugin-windicss
npm install -D vite-plugin-pwa
```
### Plugin Configuration
```javascript
import { defineConfig } from 'vite'
import { resolve } from 'path'
import legacy from '@vitejs/plugin-legacy'
import eslint from 'vite-plugin-eslint'
export default defineConfig({
plugins: [
// ESLint integration
eslint({
cache: false,
include: ['src/**/*.js', 'src/**/*.vue'],
exclude: ['node_modules', 'dist']
}),
// Legacy browser support
legacy({
targets: ['defaults', 'not IE 11']
})
]
})
```
## Decision Trees
### Choose Build Strategy
```
Need legacy browser support?
├─ Yes → Use @vitejs/plugin-legacy
└─ No → Standard build
Multiple entry points?
├─ Yes → Configure build.rollupOptions.input
└─ No → Single entry point (default)
Library vs Application?
├─ Library → Use build.lib configuration
└─ Application → Standard build config
```
### Development Workflow
```
Starting new project?
├─ Framework known → npm create vite -- --template [framework]
├─ Vanilla JS → npm create vite -- --template vanilla
└─ Experimenting → npm create vite (interactive)
Need backend integration?
├─ Same origin → Configure server.proxy
├─ Different origin → Setup CORS + proxy
└─ Mock data → Use MSW or json-server
```
## Troubleshooting
### Common Errors and Fixes
#### Module Resolution Issues
```bash
# Error: Failed to resolve import
# Fix: Check file extensions and aliases
Error: [vite] Failed to resolve import "./Component" from "src/App.jsx"
# Solutions:
# 1. Add explicit extension
import Component from './Component.jsx'
# 2. Configure resolve.extensions
export default defineConfig({
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue']
}
})
```
#### Environment Variable Not Found
```bash
# Error: import.meta.env.API_URL is undefined
# Fix: Ensure VITE_ prefix
VITE_API_URL=http://localhost:3000 # ✅ Correct
API_URL=http://localhost:3000 # ❌ Won't work
```
#### Build Optimization Issues
```bash
# Error: Some chunks are larger than 500kb
# Fix: Configure chunk splitting
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
utils: ['lodash', 'moment']
}
}
}
}
})
```
#### HMR Not Working
```bash
# Error: HMR updates not reflecting
# Fixes:
# 1. Check file watcher limits (Linux)
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
# 2. Force reload on changes
export default defineConfig({
server: {
watch: {
usePolling: true
}
}
})
```
#### Port Already in Use
```bash
# Error: Port 5173 is already in use
# Fix: Use different port or kill process
npx vite --port 3000
# or
lsof -ti:5173 | xargs kill -9
```
### Performance Optimization
```javascript
// Optimize chunk splitting
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
return 'vendor'
}
if (id.includes('src/components')) {
return 'components'
}
}
}
}
}
})
// Enable compression
import { defineConfig } from 'vite'
import { gzip } from 'rollup-plugin-gzip'
export default defineConfig({
plugins: [gzip()],
build: {
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
}
}
})
```
Install
curl -s https://skills.skynet.ceo/api/skills/vite/skill.md