Vite Installation Guide

Vite is a free and open-source next-generation frontend build tool that provides blazing fast development experience. It serves as a FOSS alternative to traditional bundlers like Create React App, webpack DevServer, or Parcel, offering instant server start, lightning-fast HMR, and optimized production builds powered by Rollup.

Development tools🟢 beginner12 min⏱️ 5-15 minutes

Vite is a free and open-source next-generation frontend build tool that provides blazing fast development experience. Created by Evan You (Vue.js creator), it serves as a FOSS alternative to traditional bundlers like Create React App, webpack DevServer, or Parcel, offering instant server start, lightning-fast HMR (Hot Module Replacement), and optimized production builds powered by Rollup.

1. Prerequisites

Hardware Requirements

  • CPU: Modern processor (1+ cores)
  • RAM: 512MB minimum (2GB+ recommended)
  • Storage: 200MB for Vite and dependencies
  • Network: Internet connection for package installation
  • Software Requirements

  • Node.js: 14.18+ or 16+ or 18+
  • Package Manager: npm, yarn, pnpm, or bun
  • Optional: Git for version control
  • Network Requirements

  • HTTPS: Access to npm registry
  • Ports:
  • 5173: Default dev server port
  • 4173: Default preview server port
  • 2. Supported Operating Systems

    Vite officially supports:

  • RHEL 8/9 and derivatives (CentOS Stream, Rocky Linux, AlmaLinux)
  • Debian 11/12
  • Ubuntu 20.04 LTS / 22.04 LTS / 24.04 LTS
  • Arch Linux
  • Alpine Linux 3.18+
  • openSUSE Leap 15.5+ / Tumbleweed
  • Fedora 38+
  • macOS 10.15+ (Catalina and later)
  • Windows 10/11
  • 3. Installation

    #### Using npm

    bash
    # Create new Vite project
    npm create vite@latest my-app
    
    # Navigate to project
    cd my-app
    
    # Install dependencies
    npm install
    
    # Start development server
    npm run dev

    #### Using yarn

    bash
    # Create new Vite project
    yarn create vite my-app
    
    # Navigate and install
    cd my-app
    yarn
    
    # Start development server
    yarn dev

    #### Using pnpm

    bash
    # Create new Vite project
    pnpm create vite my-app
    
    # Navigate and install
    cd my-app
    pnpm install
    
    # Start development server
    pnpm dev

    #### Using bun

    bash
    # Create new Vite project
    bunx create-vite my-app
    
    # Navigate and install
    cd my-app
    bun install
    
    # Start development server
    bun run dev

    Method 2: Add to Existing Project

    #### RHEL/CentOS/Rocky Linux/AlmaLinux

    bash
    # Ensure Node.js is installed
    sudo dnf install -y nodejs npm
    
    # Install Vite as dev dependency
    npm install -D vite
    
    # Add scripts to package.json
    cat > package.json << 'EOF'
    {
      "scripts": {
        "dev": "vite",
        "build": "vite build",
        "preview": "vite preview"
      },
      "devDependencies": {
        "vite": "^5.0.0"
      }
    }
    EOF
    
    # Create index.html
    cat > index.html << 'EOF'
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Vite App</title>
    </head>
    <body>
      <div id="app"></div>
      <script type="module" src="/src/main.js"></script>
    </body>
    </html>
    EOF

    #### Debian/Ubuntu

    bash
    # Install Node.js
    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
    sudo apt-get install -y nodejs
    
    # Install Vite globally (optional)
    sudo npm install -g vite
    
    # Create new project
    npm create vite@latest my-app -- --template react
    cd my-app
    npm install
    npm run dev

    #### Arch Linux

    bash
    # Install Node.js and npm
    sudo pacman -S nodejs npm
    
    # Install pnpm (recommended)
    sudo pacman -S pnpm
    
    # Create Vite project
    pnpm create vite my-app
    cd my-app
    pnpm install
    pnpm dev

    #### Alpine Linux

    bash
    # Install Node.js and npm
    apk add --no-cache nodejs npm
    
    # Create Vite project
    npm create vite@latest my-app
    cd my-app
    npm install
    npm run dev

    #### openSUSE

    bash
    # Install Node.js
    sudo zypper install -y nodejs20 npm20
    
    # Create Vite project
    npm create vite@latest my-app
    cd my-app
    npm install
    npm run dev

    #### macOS

    bash
    # Using Homebrew
    brew install node
    
    # Create Vite project
    npm create vite@latest my-app
    cd my-app
    npm install
    npm run dev

    #### Windows

    powershell
    # Using winget
    winget install OpenJS.NodeJS
    
    # Or using Chocolatey
    choco install nodejs
    
    # Create Vite project
    npm create vite@latest my-app
    cd my-app
    npm install
    npm run dev

    Method 3: Framework-Specific Templates

    bash
    # Vue
    npm create vite@latest my-vue-app -- --template vue
    
    # React
    npm create vite@latest my-react-app -- --template react
    
    # React + TypeScript
    npm create vite@latest my-react-ts-app -- --template react-ts
    
    # Preact
    npm create vite@latest my-preact-app -- --template preact
    
    # Svelte
    npm create vite@latest my-svelte-app -- --template svelte
    
    # Vanilla JavaScript
    npm create vite@latest my-vanilla-app -- --template vanilla
    
    # Vanilla TypeScript
    npm create vite@latest my-vanilla-ts-app -- --template vanilla-ts

    4. Configuration

    Basic Configuration

    Create vite.config.js:

    javascript
    import { defineConfig } from 'vite'
    
    export default defineConfig({
      // Server options
      server: {
        port: 3000,
        host: true, // Listen on all addresses
        open: true, // Open browser on start
        cors: true,
        
        // Proxy API requests
        proxy: {
          '/api': {
            target: 'http://localhost:8080',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api/, '')
          }
        }
      },
      
      // Build options
      build: {
        outDir: 'dist',
        sourcemap: true,
        minify: 'terser',
        
        // Rollup options
        rollupOptions: {
          output: {
            manualChunks: {
              vendor: ['react', 'react-dom'],
              utils: ['lodash', 'axios']
            }
          }
        }
      },
      
      // Resolve aliases
      resolve: {
        alias: {
          '@': '/src',
          '~': '/src/components'
        }
      }
    })

    TypeScript Configuration

    Create vite.config.ts:

    typescript
    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    import { resolve } from 'path'
    
    export default defineConfig({
      plugins: [react()],
      
      resolve: {
        alias: {
          '@': resolve(__dirname, './src'),
          '@components': resolve(__dirname, './src/components'),
          '@utils': resolve(__dirname, './src/utils')
        }
      },
      
      css: {
        preprocessorOptions: {
          scss: {
            additionalData: `@import "@/styles/variables.scss";`
          }
        }
      },
      
      optimizeDeps: {
        include: ['react', 'react-dom'],
        exclude: ['@vite/client']
      }
    })

    Environment Variables

    Create .env files:

    bash
    # .env
    VITE_APP_TITLE=My App
    VITE_API_URL=http://localhost:8080
    
    # .env.production
    VITE_APP_TITLE=My App (Production)
    VITE_API_URL=https://api.example.com

    Access in code:

    javascript
    console.log(import.meta.env.VITE_APP_TITLE)
    console.log(import.meta.env.VITE_API_URL)
    console.log(import.meta.env.MODE)
    console.log(import.meta.env.PROD)
    console.log(import.meta.env.DEV)

    Plugin Configuration

    javascript
    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    import legacy from '@vitejs/plugin-legacy'
    import { VitePWA } from 'vite-plugin-pwa'
    import compression from 'vite-plugin-compression'
    
    export default defineConfig({
      plugins: [
        vue(),
        
        // Legacy browser support
        legacy({
          targets: ['defaults', 'not IE 11']
        }),
        
        // PWA support
        VitePWA({
          registerType: 'autoUpdate',
          manifest: {
            name: 'My App',
            short_name: 'MyApp',
            theme_color: '#ffffff'
          }
        }),
        
        // Compression
        compression({
          algorithm: 'gzip',
          ext: '.gz'
        })
      ]
    })

    5. Service Management

    Development Server

    bash
    # Start dev server
    npm run dev
    vite
    
    # Start with custom config
    vite --config my-config.js
    
    # Start with custom port
    vite --port 8080
    
    # Start with host binding
    vite --host 0.0.0.0
    
    # Start in different mode
    vite --mode staging

    Production Build

    bash
    # Build for production
    npm run build
    vite build
    
    # Build with custom base
    vite build --base=/my-app/
    
    # Build and analyze bundle
    npm run build -- --report
    
    # Preview production build
    npm run preview
    vite preview --port 8080

    Systemd Service for Preview Server

    Create /etc/systemd/system/vite-preview.service:

    ini
    [Unit]
    Description=Vite Preview Server
    After=network.target
    
    [Service]
    Type=simple
    User=viteapp
    Group=viteapp
    WorkingDirectory=/opt/vite-app
    ExecStart=/usr/bin/npm run preview -- --port 4173 --host
    Restart=always
    RestartSec=3
    Environment=NODE_ENV=production
    
    [Install]
    WantedBy=multi-user.target
    bash
    # Create user and setup
    sudo useradd -r -s /bin/false -d /opt/vite-app viteapp
    sudo chown -R viteapp:viteapp /opt/vite-app
    
    # Build and start service
    cd /opt/vite-app
    sudo -u viteapp npm run build
    sudo systemctl daemon-reload
    sudo systemctl enable --now vite-preview

    Docker Deployment

    dockerfile
    # Multi-stage Dockerfile
    FROM node:20-alpine AS builder
    WORKDIR /app
    COPY package*.json ./
    RUN npm ci
    COPY . .
    RUN npm run build
    
    FROM nginx:alpine
    COPY --from=builder /app/dist /usr/share/nginx/html
    COPY nginx.conf /etc/nginx/conf.d/default.conf
    EXPOSE 80
    CMD ["nginx", "-g", "daemon off;"]

    6. Troubleshooting

    Common Issues

    1. Port already in use:

    bash
    # Find process using port
    lsof -i :5173
    netstat -tlnp | grep 5173
    
    # Kill process
    kill -9 <PID>
    
    # Use different port
    vite --port 3000

    2. Module resolution errors:

    bash
    # Clear cache
    rm -rf node_modules/.vite
    
    # Reinstall dependencies
    rm -rf node_modules package-lock.json
    npm install
    
    # Force dependency optimization
    vite optimize

    3. HMR not working:

    javascript
    // vite.config.js
    export default {
      server: {
        hmr: {
          overlay: true,
          protocol: 'ws',
          host: 'localhost',
          port: 5173
        }
      }
    }

    4. Build errors:

    bash
    # Increase Node.js memory
    NODE_OPTIONS="--max-old-space-size=4096" npm run build
    
    # Debug build process
    vite build --debug
    
    # Check for circular dependencies
    npx madge --circular src/

    Debug Mode

    bash
    # Enable debug logging
    DEBUG=vite:* npm run dev
    
    # Specific debug namespaces
    DEBUG=vite:resolve npm run dev
    DEBUG=vite:transform npm run dev
    DEBUG=vite:deps npm run dev
    
    # Profiling
    vite --profile

    7. Security Considerations

    Development Security

    javascript
    // vite.config.js security settings
    export default defineConfig({
      server: {
        // Restrict host access
        host: '127.0.0.1',
        
        // Configure HTTPS
        https: {
          key: fs.readFileSync('localhost-key.pem'),
          cert: fs.readFileSync('localhost.pem')
        },
        
        // Security headers
        headers: {
          'X-Content-Type-Options': 'nosniff',
          'X-Frame-Options': 'DENY',
          'X-XSS-Protection': '1; mode=block'
        }
      }
    })

    Production Security

    javascript
    // Content Security Policy
    export default defineConfig({
      build: {
        rollupOptions: {
          output: {
            // Add CSP meta tag
            banner: `<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline';">`
          }
        }
      }
    })

    Environment Variable Security

    bash
    # Never commit .env files with secrets
    echo ".env*.local" >> .gitignore
    
    # Use environment-specific files
    .env                # Default
    .env.local          # Local overrides (ignored by git)
    .env.production     # Production settings
    .env.production.local # Production secrets (ignored)

    8. Performance Tuning

    Build Optimization

    javascript
    export default defineConfig({
      build: {
        // Optimize chunk size
        chunkSizeWarningLimit: 500,
        
        // Code splitting
        rollupOptions: {
          output: {
            manualChunks(id) {
              if (id.includes('node_modules')) {
                if (id.includes('react')) {
                  return 'react-vendor';
                }
                return 'vendor';
              }
            }
          }
        },
        
        // Terser options
        terserOptions: {
          compress: {
            drop_console: true,
            drop_debugger: true
          }
        }
      }
    })

    Development Performance

    javascript
    export default defineConfig({
      // Pre-bundle dependencies
      optimizeDeps: {
        include: ['react', 'react-dom', 'axios'],
        exclude: ['@vite/client']
      },
      
      // Faster builds with esbuild
      esbuild: {
        jsxInject: `import React from 'react'`,
        jsxFactory: 'React.createElement',
        jsxFragment: 'React.Fragment'
      },
      
      // Limit file system watching
      server: {
        watch: {
          ignored: ['**/node_modules/**', '**/.git/**']
        }
      }
    })

    Caching Strategy

    javascript
    export default defineConfig({
      build: {
        rollupOptions: {
          output: {
            // Hash assets for caching
            entryFileNames: 'assets/[name].[hash].js',
            chunkFileNames: 'assets/[name].[hash].js',
            assetFileNames: 'assets/[name].[hash].[ext]'
          }
        }
      },
      
      // Service worker for caching
      plugins: [
        VitePWA({
          workbox: {
            globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
            runtimeCaching: [{
              urlPattern: /^https:\/\/api\./,
              handler: 'NetworkFirst',
              options: {
                cacheName: 'api-cache',
                expiration: {
                  maxEntries: 10,
                  maxAgeSeconds: 300
                }
              }
            }]
          }
        })
      ]
    })

    9. Backup and Restore

    Project Backup

    bash
    #!/bin/bash
    # backup-vite-project.sh
    
    PROJECT_DIR="/opt/vite-app"
    BACKUP_DIR="/var/backups/vite"
    DATE=$(date +%Y%m%d_%H%M%S)
    
    mkdir -p $BACKUP_DIR
    
    # Backup source files only
    tar -czf $BACKUP_DIR/vite_project_$DATE.tar.gz \
        -C $PROJECT_DIR \
        --exclude='node_modules' \
        --exclude='dist' \
        --exclude='.git' \
        --exclude='.vite' \
        .
    
    # Backup production build
    if [ -d "$PROJECT_DIR/dist" ]; then
        tar -czf $BACKUP_DIR/vite_dist_$DATE.tar.gz -C $PROJECT_DIR/dist .
    fi
    
    echo "Backup completed: $BACKUP_DIR/vite_project_$DATE.tar.gz"

    Configuration Export

    bash
    # Export all configuration
    mkdir -p backup/config
    cp vite.config.* backup/config/
    cp .env* backup/config/
    cp tsconfig.json backup/config/
    cp package*.json backup/config/
    
    # Create restore script
    cat > backup/restore.sh << 'EOF'
    #!/bin/bash
    cp -r config/* ../
    cd ..
    npm install
    npm run build
    EOF
    
    chmod +x backup/restore.sh

    10. System Requirements

    Minimum Requirements

  • CPU: 1 core
  • RAM: 512MB
  • Storage: 200MB
  • Node.js: 14.18+
  • CPU: 2+ cores
  • RAM: 2GB+
  • Storage: 1GB+ SSD
  • Node.js: 18+ or 20+
  • Large Project Requirements

  • CPU: 4+ cores
  • RAM: 8GB+
  • Storage: 10GB+ NVMe
  • Node.js: Latest LTS
  • 11. Support

    Official Resources

  • Website: https://vitejs.dev
  • GitHub: https://github.com/vitejs/vite
  • Documentation: https://vitejs.dev/guide/
  • Discord: https://chat.vitejs.dev
  • Community Support

  • Discord Server: https://discord.gg/vite
  • GitHub Discussions: https://github.com/vitejs/vite/discussions
  • Stack Overflow: [vite] tag
  • Twitter/X: @vite_js
  • 12. Contributing

    How to Contribute

    1. Fork the repository on GitHub

    2. Create a feature branch

    3. Submit pull request

    4. Follow TypeScript coding standards

    5. Include tests and documentation

    Development Setup

    bash
    # Clone repository
    git clone https://github.com/vitejs/vite.git
    cd vite
    
    # Install dependencies
    pnpm install
    
    # Build all packages
    pnpm build
    
    # Run tests
    pnpm test
    
    # Run specific package dev
    cd packages/vite
    pnpm dev

    13. License

    Vite is licensed under the MIT License.

    Key points:

  • Free to use, modify, and distribute
  • Commercial use allowed
  • No warranty provided
  • Attribution required
  • 14. Acknowledgments

    Credits

  • Evan You: Creator and lead developer
  • Vue.js Team: Core contributors
  • Vite Team: Maintainers and contributors
  • Rollup Team: Build tooling foundation
  • 15. Version History

    Recent Releases

  • v5.x: Current major version with improved performance
  • v4.x: Stable version with ecosystem maturity
  • v3.x: Major architectural improvements
  • Major Features by Version

  • v5.0: Rollup 4 support, performance improvements
  • v4.0: New plugin API, better HMR
  • v3.0: Vue 3 support, improved DX
  • 16. Appendices

    A. React + TypeScript Example

    typescript
    // vite.config.ts
    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    
    export default defineConfig({
      plugins: [react()],
      server: {
        port: 3000
      }
    })
    
    // src/App.tsx
    import { useState } from 'react'
    import './App.css'
    
    function App() {
      const [count, setCount] = useState(0)
    
      return (
        <div className="App">
          <h1>Vite + React + TypeScript</h1>
          <button onClick={() => setCount(count + 1)}>
            Count: {count}
          </button>
        </div>
      )
    }
    
    export default App

    B. Vue 3 Example

    javascript
    // vite.config.js
    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    
    export default defineConfig({
      plugins: [vue()]
    })
    
    // src/App.vue
    <template>
      <div>
        <h1>{{ title }}</h1>
        <button @click="count++">Count: {{ count }}</button>
      </div>
    </template>
    
    <script setup>
    import { ref } from 'vue'
    
    const title = 'Vite + Vue 3'
    const count = ref(0)
    </script>

    C. Library Mode

    javascript
    // vite.config.js for library
    import { defineConfig } from 'vite'
    import { resolve } from 'path'
    
    export default defineConfig({
      build: {
        lib: {
          entry: resolve(__dirname, 'src/index.ts'),
          name: 'MyLibrary',
          fileName: 'my-library'
        },
        rollupOptions: {
          external: ['react', 'react-dom'],
          output: {
            globals: {
              react: 'React',
              'react-dom': 'ReactDOM'
            }
          }
        }
      }
    })

    D. Custom Plugin Example

    javascript
    // my-vite-plugin.js
    export default function myPlugin() {
      return {
        name: 'my-plugin',
        
        transform(code, id) {
          if (id.endsWith('.custom')) {
            return {
              code: `export default ${JSON.stringify(code)}`,
              map: null
            }
          }
        },
        
        configureServer(server) {
          server.middlewares.use((req, res, next) => {
            console.log(req.url)
            next()
          })
        }
      }
    }
    
    // Usage in vite.config.js
    import myPlugin from './my-vite-plugin'
    
    export default defineConfig({
      plugins: [myPlugin()]
    })

    ---

    For more information and updates, visit https://github.com/howtomgr/vite