# ⚡ Vite + Emacs Integration

> Lightning-fast frontend development with seamless Emacs IDE integration

Experience the perfect marriage of modern build tooling and the world's most powerful text editor. This project demonstrates how to integrate Vite's instant Hot Module Replacement (HMR) with Emacs for an optimal development workflow.

## 🚀 Features

- **⚡ Lightning Fast HMR**: Instant updates as you type in Emacs
- **🔄 Real-time File Watching**: Automatic detection of file changes
- **🎯 Smart Completion**: Intelligent code completion and syntax highlighting
- **🖥️ Terminal Integration**: Run Vite commands directly from Emacs
- **📊 Live Status Monitoring**: Real-time build and connection status
- **🎨 Beautiful UI**: Modern, responsive interface with dark theme
- **🔧 Easy Configuration**: Simple setup with sensible defaults

## 📸 Screenshots

Visit the live demo at: **https://dev.ebrimasaye.com/vite-emacs-integration/**

## 🛠️ Quick Start

### Prerequisites

- Node.js 18+ 
- npm 9+
- Emacs 27+
- Modern web browser

### Installation

```bash
# Clone or download this project
git clone https://github.com/esaye/vite-emacs-integration.git
cd vite-emacs-integration

# Install dependencies
npm install

# Start development server
npm run dev
```

### Emacs Configuration

Add these configurations to your `~/.emacs.d/init.el`:

```elisp
;; Essential packages for web development
(use-package web-mode
  :ensure t
  :mode (("\\.vue\\'" . web-mode)
         ("\\.jsx?\\'" . web-mode)
         ("\\.tsx?\\'" . web-mode))
  :config
  (setq web-mode-content-types-alist
        '(("jsx" . "\\.jsx?\\'")))
  (setq web-mode-enable-auto-pairing t)
  (setq web-mode-enable-css-colorization t))

;; Enhanced completion
(use-package company
  :ensure t
  :hook (web-mode . company-mode)
  :config
  (setq company-idle-delay 0.1)
  (setq company-minimum-prefix-length 2))

;; Syntax checking
(use-package flycheck
  :ensure t
  :hook (web-mode . flycheck-mode))

;; Project management
(use-package projectile
  :ensure t
  :config
  (projectile-mode +1)
  (define-key projectile-mode-map (kbd "C-c p") 'projectile-command-map))

;; Git integration
(use-package magit
  :ensure t
  :bind ("C-x g" . magit-status))
```

### Advanced Emacs Integration

For the complete Vite + Emacs experience:

```elisp
;; Custom functions for Vite integration
(defun vite-dev ()
  "Start Vite development server."
  (interactive)
  (let ((default-directory (projectile-project-root)))
    (async-shell-command "npm run dev" "*Vite Dev*")))

(defun vite-build ()
  "Build project with Vite."
  (interactive)
  (let ((default-directory (projectile-project-root)))
    (compile "npm run build")))

(defun vite-preview ()
  "Start Vite preview server."
  (interactive)
  (let ((default-directory (projectile-project-root)))
    (async-shell-command "npm run preview" "*Vite Preview*")))

;; Key bindings
(global-set-key (kbd "C-c v d") 'vite-dev)
(global-set-key (kbd "C-c v b") 'vite-build)
(global-set-key (kbd "C-c v p") 'vite-preview)

;; Auto-save hook for HMR
(add-hook 'after-save-hook
          (lambda ()
            (when (and buffer-file-name
                       (string-match-p "\\.\\(js\\|ts\\|jsx\\|tsx\\|vue\\|css\\|scss\\)$"
                                       buffer-file-name))
              (message "File saved - HMR should trigger!"))))
```

## 🎯 Usage

### Development Workflow

1. **Start Vite Dev Server**
   ```bash
   npm run dev
   ```

2. **Open Emacs**
   ```bash
   emacs src/App.vue
   ```

3. **Edit and Save**
   - Make changes to your files in Emacs
   - Save with `C-x C-s`
   - Watch changes appear instantly in the browser

4. **Run Commands from Emacs**
   - `C-c v d` - Start dev server
   - `C-c v b` - Build for production
   - `C-c v p` - Preview build
   - `M-x compile` - Run custom commands

### Available Scripts

```bash
# Development
npm run dev              # Start dev server
npm run emacs:dev       # Start dev server + open Emacs

# Building
npm run build           # Build for production
npm run preview         # Preview production build
npm run emacs:build     # Build + notify Emacs

# Code Quality
npm run lint            # Lint code
npm run format          # Format code
npm run type-check      # TypeScript checking
```

## 🏗️ Project Structure

```
vite-emacs-integration/
├── src/
│   ├── components/         # Reusable components
│   ├── styles/            # CSS and styling
│   ├── utils/             # Utility functions
│   │   ├── emacs-integration.js
│   │   └── file-watcher.js
│   └── main.js            # Application entry point
├── public/                # Static assets
├── docs/                  # Documentation
├── .emacs.d/             # Emacs configuration examples
├── vite.config.js        # Vite configuration
├── package.json          # Dependencies and scripts
└── README.md             # This file
```

## 🔧 Configuration

### Vite Configuration

The `vite.config.js` includes optimizations for Emacs integration:

```javascript
export default defineConfig({
  server: {
    host: 'localhost',
    port: 3000,
    open: true,
    cors: true,
    hmr: {
      overlay: true,
    }
  },
  
  plugins: [
    // Custom Emacs integration plugin
    {
      name: 'emacs-integration',
      configureServer(server) {
        // Add middleware for Emacs communication
      }
    }
  ]
});
```

### Environment Variables

Create a `.env` file:

```env
# Development
VITE_DEV_PORT=3000
VITE_EMACS_SERVER_PORT=9000

# Emacs Integration
VITE_EMACS_WEBSOCKET_PORT=9001
VITE_ENABLE_EMACS_INTEGRATION=true

# Build
VITE_BUILD_SOURCEMAP=true
VITE_BUILD_MINIFY=true
```

## 🔌 Emacs Server Setup

For advanced integration, set up an Emacs server:

```elisp
;; Start server for external connections
(server-start)

;; Simple HTTP server for Vite integration
(defun vite-integration-server ()
  "Start a simple server for Vite integration."
  (interactive)
  (let ((process-name "vite-integration-server")
        (buffer-name "*Vite Integration Server*"))
    (when (get-process process-name)
      (delete-process process-name))
    (start-process process-name buffer-name
                   "python" "-m" "http.server" "9000")))

;; WebSocket server (requires websocket.el)
(use-package websocket
  :ensure t
  :config
  (defvar vite-websocket-server nil)
  
  (defun start-vite-websocket-server ()
    "Start WebSocket server for real-time communication."
    (interactive)
    (setq vite-websocket-server
          (websocket-server 9001
            :host 'local
            :on-message (lambda (_websocket frame)
                         (message "Received: %s" (websocket-frame-text frame)))
            :on-open (lambda (websocket)
                      (message "Vite connection opened"))
            :on-close (lambda (websocket)
                       (message "Vite connection closed"))))))
```

## 📚 Advanced Features

### Hot Module Replacement

Experience instant updates without losing application state:

```javascript
// Enable HMR for your modules
if (import.meta.hot) {
  import.meta.hot.accept('./App.vue', (newApp) => {
    // Handle hot updates
  });
}
```

### File Watching Integration

The project includes intelligent file watching:

```javascript
import { FileWatcher } from './utils/file-watcher';

const watcher = new FileWatcher();
watcher.start();

watcher.onFileChange((file) => {
  console.log('File changed:', file);
});
```

### Terminal Integration

Run Vite commands from within Emacs:

```elisp
;; Terminal integration
(defun vite-terminal-command (command)
  "Run Vite command in terminal."
  (let ((term-buffer (get-buffer-create "*Vite Terminal*")))
    (with-current-buffer term-buffer
      (term-mode)
      (term-exec term-buffer "vite" "/bin/bash" nil (list "-c" command))
      (switch-to-buffer term-buffer))))
```

## 🎨 Customization

### Themes and Styling

Customize the appearance by modifying CSS variables:

```css
:root {
  --vite-blue: #646cff;
  --emacs-purple: #7F5AB6;
  --bg-dark: #1a1a1a;
  --success: #4CAF50;
  /* Add your custom colors */
}
```

### Editor Integration

Add support for more editors:

```javascript
// Add VS Code integration
export class VSCodeIntegration {
  // Implementation for VS Code
}

// Add Vim integration  
export class VimIntegration {
  // Implementation for Vim
}
```

## 🐛 Troubleshooting

### Common Issues

**Port already in use:**
```bash
# Kill process on port 3000
npx kill-port 3000

# Or use a different port
npm run dev -- --port 3001
```

**Emacs not connecting:**
```elisp
;; Check server status
(server-running-p)

;; Restart server
(server-force-delete)
(server-start)
```

**HMR not working:**
- Ensure files are being saved
- Check console for errors
- Verify Vite dev server is running
- Restart the development server

### Performance Optimization

```javascript
// Optimize for large projects
export default defineConfig({
  optimizeDeps: {
    include: ['vue', 'vue-router']
  },
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['vue', 'vue-router']
        }
      }
    }
  }
});
```

## 📈 Performance

- **Cold Start**: < 500ms
- **HMR Updates**: < 50ms
- **Build Time**: Optimized with Rollup
- **Bundle Size**: Tree-shaken and minified

## 🤝 Contributing

Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md).

### Development Setup

```bash
# Clone the repository
git clone https://github.com/esaye/vite-emacs-integration.git

# Install dependencies
npm install

# Start development
npm run dev

# Run tests
npm test

# Build documentation
npm run docs:build
```

## 📄 License

MIT License - see [LICENSE](LICENSE) for details.

## 🙏 Acknowledgments

- [Vite](https://vitejs.dev/) - Next Generation Frontend Tooling
- [Emacs](https://www.gnu.org/software/emacs/) - The extensible editor
- [Vue.js](https://vuejs.org/) - The Progressive JavaScript Framework
- [Font Awesome](https://fontawesome.com/) - Icons and fonts

## 🔗 Links

- **Live Demo**: https://dev.ebrimasaye.com/vite-emacs-integration/
- **Documentation**: https://dev.ebrimasaye.com/vite-emacs-integration/docs/
- **GitHub**: https://github.com/esaye/vite-emacs-integration
- **Issues**: https://github.com/esaye/vite-emacs-integration/issues

---

**Made with ❤️ by [Ebrima Saye](https://ebrimasaye.com)**

*Bridging the gap between modern tooling and timeless editors.*
