# Developer Experience

> Developer Experience (DX) Patterns

- Skill: `farming-labs/developer-experience` (Agent Skill)
- Install (CLI): `npx get-skill add farming-labs/developer-experience`
- Raw SKILL.md: https://api.skillmd.com/api/skills/farming-labs/developer-experience/raw
- Safety review: pending (external: skill-scanner PASS, skillspector CAUTION)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: farming-labs (https://skillmd.com/u/farming-labs)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/farming-labs/developer-experience

---

# Developer Experience (DX) Patterns

## Overview

Developer Experience encompasses the tools, workflows, and feedback loops that make building applications fast and enjoyable. Modern frameworks compete heavily on DX—instant hot reloading, meaningful error messages, and zero-config setups have become table stakes.

This skill covers the architecture behind great DX: how dev servers work, what makes HMR possible, why Vite changed everything, and how to build developer tools that delight.

## Prerequisites

- Understanding of [build-pipelines-bundling](../build-pipelines-bundling/SKILL.md)
- Familiarity with [meta-frameworks-overview](../meta-frameworks-overview/SKILL.md)
- Basic knowledge of module systems (ESM, CommonJS)

---

## The Evolution of Dev Servers

```
TRADITIONAL BUNDLER-BASED DEV (Webpack, 2015-2020):

Source Files ──► Full Bundle ──► Dev Server ──► Browser
     │              │                              │
     │         (slow!)                             │
     │              │                              │
     └── Change ───►│◄──── Rebuild entire bundle ──┘
                    │
              (seconds to minutes)


MODERN UNBUNDLED DEV (Vite, 2020+):

Source Files ──► Dev Server ──► Browser (native ESM)
     │              │                │
     │         (instant!)            │
     │              │                │
     └── Change ───►│◄─── Only transform changed file
                    │
              (milliseconds)
```

### Why Traditional Bundling Was Slow

```javascript
// THE COLD START PROBLEM

// Traditional dev server startup:
// 1. Scan all files in project
// 2. Parse every file to find imports
// 3. Build complete dependency graph
// 4. Transform all files (JSX, TypeScript, etc.)
// 5. Bundle everything into one or few files
// 6. Start server and serve bundle

// For a large project (10,000+ modules):
// - Startup time: 30 seconds to 2+ minutes
// - Each save: 5-30 seconds to rebuild

// THE BUNDLING TAX
// Every file change requires:
// 1. Invalidate affected modules
// 2. Re-transform changed files
// 3. Re-bundle affected chunks
// 4. Send entire chunk to browser
// 5. Browser re-executes entire chunk
```

### The Unbundled Revolution

```javascript
// VITE'S KEY INSIGHT:
// Browsers now support ES Modules natively!
// Why bundle during development at all?

// Instead of:
import { Button } from './components/Button.bundle.js';

// Browser can directly load:
import { Button } from './components/Button.tsx';
// Dev server transforms on-the-fly and serves

// BENEFITS:
// ✓ No bundling step - instant server start
// ✓ On-demand transformation - only transform what's requested
// ✓ Native browser caching - unchanged files stay cached
// ✓ True HMR - update single module, not entire chunk
```

---

## Hot Module Replacement (HMR) Deep Dive

### What is HMR?

```
WITHOUT HMR (Full Page Reload):

Code Change → Rebuild → Reload Page → Lose All State
                                           │
                                    ┌──────┴──────┐
                                    │ Form data   │
                                    │ Scroll pos  │
                                    │ Modal state │
                                    │ User input  │
                                    └─────────────┘
                                        (LOST!)


WITH HMR (Hot Update):

Code Change → Transform File → Patch Module → State Preserved!
                                     │
                              ┌──────┴──────┐
                              │ Component   │
                              │ re-renders  │
                              │ with new    │
                              │ code, state │
                              │ intact      │
                              └─────────────┘
```

### HMR Protocol

```javascript
// HMR operates through a WebSocket connection:

// 1. SERVER → CLIENT: Connection established
{ type: 'connected' }

// 2. SERVER → CLIENT: File changed, here's what to update
{
  type: 'update',
  updates: [{
    type: 'js-update',
    path: '/src/components/Button.tsx',
    acceptedPath: '/src/components/Button.tsx',
    timestamp: 1699123456789
  }]
}

// 3. CLIENT: Fetches new module
GET /src/components/Button.tsx?t=1699123456789

// 4. CLIENT: Replaces old module, calls accept callback
import.meta.hot.accept(() => {
  // Re-render with new component
});

// 5. SERVER → CLIENT: Full reload needed (can't HMR)
{ type: 'full-reload', path: '/src/main.tsx' }
```

### HMR Boundaries

```javascript
// HMR BOUNDARY: A module that "accepts" hot updates

// ✓ HMR BOUNDARY - accepts updates
// Button.tsx
export function Button({ children }) {
  return <button className="btn">{children}</button>;
}

// Vite/React plugin auto-injects:
if (import.meta.hot) {
  import.meta.hot.accept();
}


// ✗ NOT A BOUNDARY - updates bubble up
// utils.ts (no accept call)
export function formatDate(date) {
  return date.toISOString();
}


// HOW UPDATES PROPAGATE:
//
//     main.tsx (boundary)
//         │
//    ┌────┴────┐
//    │         │
// App.tsx   utils.ts ◄── Change here
//    │         │
// Button.tsx   │
//    │         │
//    └────┬────┘
//         │
//         ▼
// Update bubbles up to nearest boundary (main.tsx)
// If no boundary found → full page reload
// This means it will be bubble to those needs it. 
```

### React Fast Refresh

```javascript
// REACT FAST REFRESH: HMR that preserves React state

// How it works:
// 1. Detect which exports are React components
// 2. Wrap each component to capture its state
// 3. On update, re-render with new code, inject old state

// WHAT GETS PRESERVED:
// ✓ useState values
// ✓ useRef values  
// ✓ Component local state

// WHAT TRIGGERS FULL REMOUNT:
// ✗ Changed hooks order
// ✗ Changed hook dependencies
// ✗ Class components (legacy)
// ✗ Non-component exports mixed in


// FAST REFRESH BOUNDARIES:

// ✓ Good - only React components
// Button.tsx
export function Button() { ... }
export function IconButton() { ... }

// ✗ Bad - mixed exports force full reload
// Button.tsx
export function Button() { ... }
export const BUTTON_SIZES = ['sm', 'md', 'lg']; // Not a component!

// Solution: separate non-component exports
// constants.ts
export const BUTTON_SIZES = ['sm', 'md', 'lg'];
```

---

## Vite Architecture Deep Dive

### Core Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                         VITE                                 │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐  │
│  │   Connect    │    │   Module     │    │    Plugin    │  │
│  │   Server     │    │   Graph      │    │   Container  │  │
│  │              │    │              │    │              │  │
│  │ • HTTP       │    │ • Dependency │    │ • Transform  │  │
│  │ • WebSocket  │    │   tracking   │    │ • Resolve    │  │
│  │ • Middleware │    │ • HMR edges  │    │ • Load       │  │
│  └──────────────┘    └──────────────┘    └──────────────┘  │
│         │                   │                   │           │
│         └───────────────────┼───────────────────┘           │
│                             │                               │
│  ┌──────────────────────────┴──────────────────────────┐   │
│  │                    esbuild                            │   │
│  │  • Pre-bundle dependencies (node_modules)            │   │
│  │  • TypeScript/JSX transform (fast path)              │   │
│  └───────────────────────────────────────────────────────┘   │
│                                                              │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                       BROWSER                                │
│  • Native ES Modules                                        │
│  • Import maps (optional)                                   │
│  • Module-level caching                                     │
└─────────────────────────────────────────────────────────────┘
```

### Dependency Pre-Bundling

```javascript
// THE PROBLEM: node_modules aren't ESM-ready

// 1. CommonJS modules (can't be loaded natively)
const lodash = require('lodash');

// 2. Many small files (hundreds of requests)
// lodash-es has 600+ individual modules!
import debounce from 'lodash-es/debounce';
// Browser would make 600+ HTTP requests

// 3. Different export formats
// Some packages: module.exports = ...
// Some packages: export default ...
// Some packages: export { named }


// VITE'S SOLUTION: Pre-bundle with esbuild

// On first run, Vite:
// 1. Scans your code for bare imports
import React from 'react';
import { debounce } from 'lodash-es';

// 2. Pre-bundles each dependency into single ESM file
// node_modules/.vite/deps/react.js
// node_modules/.vite/deps/lodash-es.js

// 3. Rewrites imports to point to pre-bundled versions
import React from '/node_modules/.vite/deps/react.js?v=abc123';

// BENEFITS:
// ✓ CommonJS → ESM conversion
// ✓ 600 files → 1 file (fewer requests)
// ✓ Cached until dependency changes
// ✓ Done with esbuild (incredibly fast)
```

### The Transform Pipeline

```javascript
// REQUEST LIFECYCLE IN VITE:

// 1. Browser requests module
GET /src/components/Button.tsx

// 2. Vite intercepts, runs through plugins
async function transformRequest(url) {
  // Resolve: determine actual file path
  const resolved = await pluginContainer.resolveId(url);
  // → /Users/you/project/src/components/Button.tsx
  
  // Load: read file contents (or virtual module)
  const loaded = await pluginContainer.load(resolved.id);
  // → "import React from 'react';\nexport function Button..."
  
  // Transform: convert to browser-ready code
  const transformed = await pluginContainer.transform(loaded.code, resolved.id);
  // → TypeScript compiled, JSX transformed, imports rewritten
  
  return transformed;
}

// 3. Serve transformed code with proper headers
// Content-Type: application/javascript
// Cache-Control: max-age=31536000 (if dependency)
// Cache-Control: no-cache (if source file)
```

### Import Rewriting

```javascript
// VITE REWRITES ALL IMPORTS:

// Your code:
import React from 'react';
import { useState } from 'react';
import Button from './Button';
import styles from './App.module.css';
import logo from './logo.svg';

// After Vite transforms:
import React from '/node_modules/.vite/deps/react.js?v=abc123';
import { useState } from '/node_modules/.vite/deps/react.js?v=abc123';
import Button from '/src/Button.tsx?t=1699123456789';
import styles from '/src/App.module.css?t=1699123456789';
import logo from '/src/logo.svg';

// WHY THE QUERY PARAMS?
// ?v=abc123  → Content hash for dependencies (long cache)
// ?t=16991.. → Timestamp for source files (bust cache on change)

// HOW IT WORKS:
function rewriteImports(code, importer) {
  // Parse with es-module-lexer (fast!)
  const [imports] = parse(code);
  
  let result = code;
  for (const imp of imports.reverse()) { // reverse to preserve positions
    const resolved = resolveImport(imp.n, importer);
    result = result.slice(0, imp.s) + resolved + result.slice(imp.e);
  }
  
  return result;
}
```

---

## Error Overlays

### The Error Overlay Experience

```
┌─────────────────────────────────────────────────────────────┐
│  ✕                                                      [x] │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  TypeError: Cannot read property 'map' of undefined         │
│                                                              │
│  ┌─────────────────────────────────────────────────────────┐│
│  │  12 │   return (                                        ││
│  │  13 │     <ul>                                          ││
│  │▶ 14 │       {items.map(item => (                        ││
│  │  15 │         <li key={item.id}>{item.name}</li>        ││
│  │  16 │       ))}                                         ││
│  └─────────────────────────────────────────────────────────┘│
│                                                              │
│  src/components/List.tsx:14:15                              │
│                                                              │
│  Click outside or fix the error to dismiss                  │
│                                                              │
└─────────────────────────────────────────────────────────────┘
```

### Types of Errors

```javascript
// 1. COMPILE-TIME ERRORS (caught during transform)
// - Syntax errors
// - TypeScript errors
// - Invalid imports

// Example: SyntaxError
const x = {
  foo: 'bar'
  baz: 'qux'  // Missing comma
};

// Overlay shows:
// SyntaxError: Unexpected token (line 3)
// With syntax-highlighted code frame


// 2. RUNTIME ERRORS (caught in browser)
// - Undefined variables
// - Type errors
// - Failed assertions

// Example: TypeError
function Component({ items }) {
  return items.map(i => <div>{i}</div>); // items is undefined
}

// Overlay shows:
// TypeError: Cannot read property 'map' of undefined
// With stack trace mapped to source


// 3. HMR ERRORS (caught during hot update)
// - Failed module execution
// - React hooks violations

// Overlay shows:
// [hmr] Failed to reload /src/App.tsx
// With specific error and suggestion
```

### Source Maps for Better Errors

```javascript
// WITHOUT SOURCE MAPS:
// Error at bundle.js:15847:23
// 😱 Good luck finding that!

// WITH SOURCE MAPS:
// Error at src/components/Button.tsx:42:15
// 🎯 Exactly where you need to look!


// HOW SOURCE MAPS WORK:
//
// Original (Button.tsx):          Compiled (Button.js):
// Line 1: import React...    →    Line 1: import React...
// Line 2:                    →    Line 2: 
// Line 3: export function... →    Line 3: export function...
// Line 4:   const [x, set]   →    Line 4:   const [x, set]
//          ↑ column 8        →           ↑ column 8
//
// Source Map (Button.js.map):
// {
//   "mappings": "AAAA,OAAO,QAAQ,...",
//   "sources": ["Button.tsx"],
//   "sourcesContent": ["import React..."]
// }

// The "mappings" field encodes:
// - Output line/column → Source line/column
// - Uses VLQ encoding for compactness
```

---

## File Watching

### Chokidar: The Standard File Watcher

```javascript
// VITE USES CHOKIDAR FOR FILE WATCHING

import chokidar from 'chokidar';

const watcher = chokidar.watch('src', {
  ignored: [
    '**/node_modules/**',
    '**/.git/**',
  ],
  ignoreInitial: true,  // Don't fire for existing files
  ignorePermissionErrors: true,
});

watcher
  .on('change', (path) => {
    // File modified
    handleFileChange(path);
  })
  .on('add', (path) => {
    // New file created
    handleNewFile(path);
  })
  .on('unlink', (path) => {
    // File deleted
    handleFileDelete(path);
  });


// DEBOUNCING RAPID CHANGES:
// IDEs often save multiple times quickly

let pendingChanges = new Set();
let timeout = null;

function handleFileChange(path) {
  pendingChanges.add(path);
  
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    processChanges([...pendingChanges]);
    pendingChanges.clear();
  }, 50); // Wait 50ms for more changes
}
```

### Platform-Specific Watching

```javascript
// FILE WATCHING IS OS-SPECIFIC:

// macOS: FSEvents (fast, efficient)
// - Uses kernel-level events
// - Low CPU usage
// - Handles large directories well

// Linux: inotify (good, some limits)
// - Kernel-level events
// - Watch limit: /proc/sys/fs/inotify/max_user_watches
// - May need: echo 524288 | sudo tee /proc/sys/fs/inotify/max_user_watches

// Windows: ReadDirectoryChangesW (okay, some issues)
// - Can miss rapid changes
// - Network drives problematic
// - WSL2 has cross-filesystem issues


// POLLING FALLBACK:
// When native watching fails, poll every N ms

chokidar.watch('src', {
  usePolling: true,        // Force polling
  interval: 100,           // Check every 100ms
  binaryInterval: 300,     // Less frequent for binaries
});
```

---

## Module Graph

### Tracking Dependencies

```javascript
// THE MODULE GRAPH: Heart of HMR

class ModuleGraph {
  constructor() {
    // URL → ModuleNode
    this.urlToModuleMap = new Map();
    // File path → ModuleNode
    this.fileToModulesMap = new Map();
  }
}

class ModuleNode {
  constructor(url) {
    this.url = url;
    this.file = null;
    this.importers = new Set();   // Who imports this module
    this.importedModules = new Set(); // What this module imports
    this.acceptedHmrDeps = new Set(); // HMR boundaries
    this.transformResult = null;  // Cached transform
    this.lastHMRTimestamp = 0;
  }
}

// EXAMPLE GRAPH:
//
//                    main.tsx
//                       │
//              ┌────────┴────────┐
//              ▼                 ▼
//           App.tsx          utils.ts
//              │                 │
//      ┌───────┼───────┐         │
//      ▼       ▼       ▼         │
//  Header  Content  Footer       │
//      │       │       │         │
//      └───────┴───────┴─────────┘
//              │
//              ▼
//          Button.tsx
```

### Invalidation and Propagation

```javascript
// WHEN A FILE CHANGES:

function handleFileChange(file) {
  const modules = moduleGraph.getModulesByFile(file);
  
  for (const mod of modules) {
    // 1. Invalidate this module's cache
    mod.transformResult = null;
    
    // 2. Find update boundaries
    const boundaries = propagateUpdate(mod);
    
    // 3. Send update to client
    if (boundaries.size > 0) {
      ws.send({
        type: 'update',
        updates: [...boundaries].map(b => ({
          type: 'js-update',
          path: b.url,
          timestamp: Date.now(),
        })),
      });
    } else {
      // No boundary found - full reload
      ws.send({ type: 'full-reload' });
    }
  }
}

function propagateUpdate(node, boundaries = new Set(), visited = new Set()) {
  if (visited.has(node)) return boundaries;
  visited.add(node);
  
  // Is this module an HMR boundary?
  if (node.acceptedHmrDeps.has(node)) {
    boundaries.add(node);
    return boundaries;
  }
  
  // Propagate to importers
  for (const importer of node.importers) {
    propagateUpdate(importer, boundaries, visited);
  }
  
  return boundaries;
}
```

---

## CSS Hot Update

### CSS HMR Without JavaScript

```javascript
// CSS CAN BE HOT-UPDATED WITHOUT JS EXECUTION!

// 1. Browser loads stylesheet
<link rel="stylesheet" href="/src/App.css">

// 2. File changes, Vite detects
// 3. Vite sends update message
{ type: 'css-update', path: '/src/App.css', timestamp: 123456 }

// 4. Client adds cache-busting param
const link = document.querySelector('link[href*="App.css"]');
link.href = '/src/App.css?t=123456';

// 5. Browser fetches new stylesheet
// 6. Styles update instantly - no flash!


// WHY NO FLASH?
// - Old stylesheet stays active until new one loads
// - Browser swaps atomically
// - No JavaScript re-execution needed
```

### CSS Modules HMR

```javascript
// CSS MODULES ARE TRICKIER:

// styles.module.css
.button {
  color: red;
}

// Compiles to:
export default {
  button: 'button_abc123'
};

// On HMR:
// 1. Update the stylesheet (visual change)
// 2. Update the JS module (class name mapping)
// 3. Components using new class names re-render


// VITE'S CSS MODULE TRANSFORM:
function transformCSSModule(css, id) {
  const { code, map, modules } = compileCSSModules(css);
  // since we can not run logic & doesn't have all the primitive we need in css. we need to hook it with client js. 
  return `
import { updateStyle } from '/@vite/client';
const css = ${JSON.stringify(code)};
updateStyle(${JSON.stringify(id)}, css);
export default ${JSON.stringify(modules)};

if (import.meta.hot) {
  import.meta.hot.accept();
}
  `;
}
```

---

## TypeScript in Development

### Why Not tsc?

```javascript
// TYPESCRIPT COMPILER (tsc) IS SLOW:
// - Full type checking
// - Reads entire project
// - Builds complete type graph
// - Emits declarations

// FOR DEV SERVER, WE ONLY NEED:
// - Strip type annotations
// - Transform enums/decorators
// - Convert TSX

// SOLUTION: Use esbuild for transform, skip type checking

// esbuild transform (< 1ms per file):
import { transform } from 'esbuild';

const result = await transform(code, {
  loader: 'tsx',
  target: 'esnext',
});

// vs tsc (100ms+ for project):
// Full project analysis, type checking, etc.


// TYPE CHECKING SEPARATELY:
// Run tsc in a separate process, show errors in overlay

// vite.config.ts
import checker from 'vite-plugin-checker';

export default {
  plugins: [
    checker({
      typescript: true, // Runs tsc --noEmit in background
    }),
  ],
};
```

### SWC: Even Faster Transforms

```javascript
// SWC (Speedy Web Compiler) - Rust-based

// Transform benchmarks (10,000 files):
// Babel:   45 seconds
// esbuild: 0.5 seconds
// SWC:     0.3 seconds

// Vite can use SWC for React:
import react from '@vitejs/plugin-react-swc';

export default {
  plugins: [react()],
};

// SWC FEATURES:
// ✓ TypeScript transform
// ✓ JSX transform
// ✓ React Fast Refresh
// ✓ Decorators
// ✓ Minification
```

---

## Proxy and API Mocking

### Development Proxy

```javascript
// PROXY API REQUESTS TO BACKEND

// vite.config.ts
export default {
  server: {
    proxy: {
      // /api/users → http://localhost:8080/api/users
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
      },
      
      // /graphql → http://localhost:4000/graphql
      '/graphql': {
        target: 'http://localhost:4000',
        changeOrigin: true,
      },
      
      // Rewrite paths
      '/old-api': {
        target: 'http://localhost:8080',
        rewrite: (path) => path.replace(/^\/old-api/, '/v2'),
      },
      
      // WebSocket proxy
      '/ws': {
        target: 'ws://localhost:8080',
        ws: true,
      },
    },
  },
};


// HOW PROXY WORKS:
// 1. Browser requests: http://localhost:5173/api/users
// 2. Vite intercepts, sees /api prefix
// 3. Vite forwards to: http://localhost:8080/api/users
// 4. Backend responds
// 5. Vite forwards response to browser
// 6. No CORS issues! (same origin from browser's view)
```

### Mock Service Worker (MSW)

```javascript
// MOCK APIs WITHOUT BACKEND

// mocks/handlers.ts
import { rest } from 'msw';

export const handlers = [
  rest.get('/api/users', (req, res, ctx) => {
    return res(
      ctx.json([
        { id: 1, name: 'Alice' },
        { id: 2, name: 'Bob' },
      ])
    );
  }),
  
  rest.post('/api/users', async (req, res, ctx) => {
    const body = await req.json();
    return res(
      ctx.status(201),
      ctx.json({ id: 3, ...body })
    );
  }),
  
  // Simulate errors
  rest.get('/api/error', (req, res, ctx) => {
    return res(ctx.status(500), ctx.json({ error: 'Server error' }));
  }),
  
  // Simulate latency
  rest.get('/api/slow', (req, res, ctx) => {
    return res(ctx.delay(2000), ctx.json({ data: 'slow response' }));
  }),
];

// mocks/browser.ts
import { setupWorker } from 'msw';
import { handlers } from './handlers';

export const worker = setupWorker(...handlers);

// main.tsx
if (process.env.NODE_ENV === 'development') {
  const { worker } = await import('./mocks/browser');
  await worker.start();
}
```

---

## Dev Server Middleware

### Custom Middleware in Vite

```javascript
// vite.config.ts
export default {
  plugins: [
    {
      name: 'custom-middleware',
      configureServer(server) {
        // Runs BEFORE Vite's middleware
        server.middlewares.use((req, res, next) => {
          if (req.url === '/__custom') {
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify({ status: 'ok' }));
            return;
          }
          next();
        });
        
        // Runs AFTER Vite's middleware (return function)
        return () => {
          server.middlewares.use((req, res, next) => {
            // Post-middleware logic
            next();
          });
        };
      },
    },
  ],
};


// COMMON MIDDLEWARE USE CASES:

// 1. Custom API routes
configureServer(server) {
  server.middlewares.use('/api', (req, res, next) => {
    // Handle API
  });
}

// 2. Server-sent events for live data
configureServer(server) {
  server.middlewares.use('/__events', (req, res) => {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
    });
    
    const interval = setInterval(() => {
      res.write(`data: ${JSON.stringify({ time: Date.now() })}\n\n`);
    }, 1000);
    
    req.on('close', () => clearInterval(interval));
  });
}

// 3. Authentication mock
configureServer(server) {
  server.middlewares.use((req, res, next) => {
    if (req.url.startsWith('/api/')) {
      req.headers['x-user-id'] = 'dev-user-123';
    }
    next();
  });
}
```

---

## Zero-Config Philosophy

### Convention Over Configuration

```javascript
// VITE'S ZERO-CONFIG DEFAULTS:

// 1. Entry point: index.html (not JS!)
// 2. Source directory: / (root)
// 3. Output directory: dist/
// 4. Dev port: 5173
// 5. Asset handling: automatic
// 6. CSS: just import it
// 7. TypeScript: works out of the box
// 8. JSX: auto-detected


// MINIMAL SETUP:
// package.json
{
  "scripts": {
    "dev": "vite",
    "build": "vite build"
  },
  "devDependencies": {
    "vite": "^5.0.0"
  }
}

// index.html
<!DOCTYPE html>
<html>
<body>
  <div id="root"></div>
  <script type="module" src="/src/main.tsx"></script>
</body>
</html>

// That's it! No config file needed.


// FRAMEWORK PRESETS:
npm create vite@latest my-app -- --template react-ts
npm create vite@latest my-app -- --template vue
npm create vite@latest my-app -- --template svelte
```

### Sensible Defaults with Escape Hatches

```javascript
// DEFAULTS CAN BE OVERRIDDEN:

// vite.config.ts
export default {
  // Change root
  root: 'src',
  
  // Change output
  build: {
    outDir: '../build',
  },
  
  // Change public dir
  publicDir: 'static',
  
  // Custom port
  server: {
    port: 3000,
    open: true, // Auto-open browser
  },
  
  // Alias paths
  resolve: {
    alias: {
      '@': '/src',
      '@components': '/src/components',
    },
  },
};
```

---

## Beyond Vite: Other DX Tools

### Turbopack (Next.js)

```javascript
// TURBOPACK: Incremental bundler by Vercel

// Key differences from Vite:
// 1. Bundler-based (like Webpack) but incremental
// 2. Rust-based (like SWC)
// 3. Function-level caching
// 4. Designed for Next.js specifically

// Turbo's approach:
// - Don't re-transform unchanged functions
// - Cache at granular level
// - Parallelize everything

// Enable in Next.js:
next dev --turbo
```

### Bun as Dev Server

```javascript
// BUN: All-in-one JavaScript runtime

// Bun is FAST:
// - Written in Zig
// - Uses JavaScriptCore (not V8)
// - Native bundler/transpiler
// - Native test runner

// Bun dev server:
bun --hot src/index.tsx

// Bun's advantages:
// ✓ Single binary (no npm install)
// ✓ Faster npm install
// ✓ Native TypeScript
// ✓ Built-in test runner
// ✓ Built-in bundler

// Bun's tradeoffs:
// ✗ Less mature ecosystem
// ✗ Some Node.js incompatibilities
// ✗ Smaller plugin ecosystem
```

### Modern Alternatives Comparison

```
┌────────────┬──────────┬────────────┬─────────────┬─────────┐
│            │ Vite     │ Turbopack  │ Bun         │ Parcel  │
├────────────┼──────────┼────────────┼─────────────┼─────────┤
│ Language   │ TS/JS    │ Rust       │ Zig         │ Rust/JS │
├────────────┼──────────┼────────────┼─────────────┼─────────┤
│ Approach   │ Unbundled│ Incremental│ All-in-one  │ Zero-cfg│
├────────────┼──────────┼────────────┼─────────────┼─────────┤
│ Dev Mode   │ ESM      │ Bundled    │ ESM         │ ESM     │
├────────────┼──────────┼────────────┼─────────────┼─────────┤
│ Framework  │ Agnostic │ Next.js    │ Agnostic    │ Agnostic│
├────────────┼──────────┼────────────┼─────────────┼─────────┤
│ Plugins    │ Rollup   │ Webpack*   │ Limited     │ Own     │
├────────────┼──────────┼────────────┼─────────────┼─────────┤
│ Maturity   │ Stable   │ Beta       │ Stable      │ Stable  │
└────────────┴──────────┴────────────┴─────────────┴─────────┘

* Turbopack aims for Webpack plugin compatibility
```

---

## Deep Dive: Building a Minimal Dev Server

### Core Implementation

```javascript
// A SIMPLIFIED DEV SERVER (educational)

import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { WebSocketServer } from 'ws';
import chokidar from 'chokidar';
import { transform } from 'esbuild';

class DevServer {
  constructor(root = process.cwd()) {
    this.root = root;
    this.moduleGraph = new Map();
    this.clients = new Set();
  }
  
  async start(port = 3000) {
    // HTTP server for files
    this.httpServer = createServer(this.handleRequest.bind(this));
    
    // WebSocket for HMR
    this.wss = new WebSocketServer({ server: this.httpServer });
    this.wss.on('connection', (ws) => {
      this.clients.add(ws);
      ws.on('close', () => this.clients.delete(ws));
    });
    
    // File watcher
    this.watcher = chokidar.watch(this.root, {
      ignored: /node_modules/,
      ignoreInitial: true,
    });
    this.watcher.on('change', this.handleFileChange.bind(this));
    
    this.httpServer.listen(port, () => {
      console.log(`Dev server running at http://localhost:${port}`);
    });
  }
  
  async handleRequest(req, res) {
    let url = req.url;
    
    // Serve index.html for root
    if (url === '/') {
      url = '/index.html';
    }
    
    try {
      if (url.endsWith('.html')) {
        await this.serveHtml(url, res);
      } else if (url.endsWith('.ts') || url.endsWith('.tsx')) {
        await this.serveTypeScript(url, res);
      } else if (url.endsWith('.css')) {
        await this.serveCss(url, res);
      } else {
        await this.serveStatic(url, res);
      }
    } catch (error) {
      res.writeHead(500);
      res.end(error.message);
    }
  }
  
  async serveHtml(url, res) {
    let html = await readFile(this.root + url, 'utf-8');
    
    // Inject HMR client
    html = html.replace(
      '</head>',
      `<script type="module" src="/@hmr-client"></script></head>`
    );
    
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(html);
  }
  
  async serveTypeScript(url, res) {
    const filePath = this.root + url.split('?')[0];
    const code = await readFile(filePath, 'utf-8');
    
    // Transform with esbuild
    const result = await transform(code, {
      loader: url.endsWith('.tsx') ? 'tsx' : 'ts',
      sourcemap: 'inline',
      target: 'esnext',
    });
    
    // Rewrite imports and inject HMR
    const transformed = this.transformImports(result.code, url);
    
    // Track in module graph
    this.moduleGraph.set(url, {
      code: transformed,
      timestamp: Date.now(),
    });
    
    res.writeHead(200, { 'Content-Type': 'application/javascript' });
    res.end(transformed);
  }
  
  transformImports(code, importer) {
    // Simple import rewriting (real impl uses es-module-lexer)
    code = code.replace(
      /from ['"](.+)['"]/g,
      (match, path) => {
        if (path.startsWith('.')) {
          return `from '${path}?t=${Date.now()}'`;
        }
        return match;
      }
    );
    
    // Inject HMR
    code += `
if (import.meta.hot) {
  import.meta.hot.accept();
}`;
    
    return code;
  }
  
  handleFileChange(file) {
    const url = file.replace(this.root, '');
    
    // Invalidate cache
    this.moduleGraph.delete(url);
    
    // Notify clients
    this.broadcast({
      type: 'update',
      path: url,
      timestamp: Date.now(),
    });
  }
  
  broadcast(message) {
    const data = JSON.stringify(message);
    for (const client of this.clients) {
      client.send(data);
    }
  }
}

// HMR Client (served at /@hmr-client)
const hmrClient = `
const socket = new WebSocket('ws://' + location.host);

socket.onmessage = async (event) => {
  const data = JSON.parse(event.data);
  
  if (data.type === 'update') {
    // Fetch new module
    const newModule = await import(data.path + '?t=' + data.timestamp);
    console.log('[HMR] Updated:', data.path);
  }
};

// Expose to modules
import.meta.hot = {
  accept(cb) {
    // Register callback
  },
};
`;
```

---

## For Framework Authors: Building DX Systems

> **Implementation Note**: The patterns and code examples below represent one proven approach to building developer experience systems. Different tools take different approaches—Vite uses native ESM, Turbopack uses incremental compilation, and Bun uses a unified runtime. The direction shown here is based on the unbundled dev server pattern popularized by Vite. Adapt based on your framework's bundler integration, target audience, and whether you need custom transform pipelines.

### Implementing an HMR Runtime

```javascript
// CLIENT-SIDE HMR RUNTIME

class HMRRuntime {
  constructor() {
    this.socket = null;
    this.registeredModules = new Map();
    this.pendingUpdates = [];
    this.isConnected = false;
  }
  
  connect(url) {
    this.socket = new WebSocket(url);
    
    this.socket.onopen = () => {
      this.isConnected = true;
      console.log('[HMR] Connected');
      this.flushPendingUpdates();
    };
    
    this.socket.onmessage = (event) => {
      const message = JSON.parse(event.data);
      this.handleMessage(message);
    };
    
    this.socket.onclose = () => {
      this.isConnected = false;
      console.log('[HMR] Disconnected, attempting reconnect...');
      setTimeout(() => this.connect(url), 1000);
    };
  }
  
  handleMessage(message) {
    switch (message.type) {
      case 'connected':
        console.log('[HMR] Server connected');
        break;
        
      case 'update':
        this.handleUpdate(message.updates);
        break;
        
      case 'full-reload':
        console.log('[HMR] Full reload required');
        location.reload();
        break;
        
      case 'error':
        this.showErrorOverlay(message.error);
        break;
        
      case 'prune':
        // Remove stale modules
        for (const path of message.paths) {
          this.registeredModules.delete(path);
        }
        break;
    }
  }
  
  async handleUpdate(updates) {
    const modulesToUpdate = [];
    
    for (const update of updates) {
      if (update.type === 'js-update') {
        modulesToUpdate.push(update);
      } else if (update.type === 'css-update') {
        this.updateCSS(update.path, update.timestamp);
      }
    }
    
    // Batch JavaScript updates
    if (modulesToUpdate.length > 0) {
      await this.applyJSUpdates(modulesToUpdate);
    }
  }
  
  async applyJSUpdates(updates) {
    const toApply = [];
    
    for (const { path, timestamp, acceptedPath } of updates) {
      const mod = this.registeredModules.get(acceptedPath);
      
      if (!mod) {
        // Module not registered, needs full reload
        console.warn(`[HMR] ${path} is not HMR-compatible, reloading`);
        location.reload();
        return;
      }
      
      toApply.push({ mod, path, timestamp });
    }
    
    // Apply updates
    for (const { mod, path, timestamp } of toApply) {
      try {
        // Dispose old module if needed
        if (mod.disposeCallback) {
          await mod.disposeCallback();
        }
        
        // Fetch new module
        const newUrl = `${path}?t=${timestamp}`;
        const newModule = await import(/* @vite-ignore */ newUrl);
        
        // Call accept callback
        if (mod.acceptCallback) {
          await mod.acceptCallback(newModule);
        }
        
        console.log(`[HMR] Updated ${path}`);
      } catch (error) {
        console.error(`[HMR] Failed to apply update for ${path}`, error);
        this.showErrorOverlay({
          message: error.message,
          stack: error.stack,
          file: path,
        });
      }
    }
  }
  
  updateCSS(path, timestamp) {
    // Find existing link
    const links = document.querySelectorAll('link[rel="stylesheet"]');
    for (const link of links) {
      if (link.href.includes(path)) {
        // Update href to bust cache
        const url = new URL(link.href);
        url.searchParams.set('t', timestamp);
        link.href = url.toString();
        console.log(`[HMR] Updated CSS ${path}`);
        return;
      }
    }
    
    // Link not found, insert new one
    const newLink = document.createElement('link');
    newLink.rel = 'stylesheet';
    newLink.href = `${path}?t=${timestamp}`;
    document.head.appendChild(newLink);
  }
  
  // Called by modules via import.meta.hot.accept()
  registerModule(path, callbacks) {
    this.registeredModules.set(path, callbacks);
  }
  
  // Create import.meta.hot API for a module
  createHotContext(ownerPath) {
    const hot = {
      accept: (deps, callback) => {
        if (typeof deps === 'function' || !deps) {
          // Self-accepting
          this.registerModule(ownerPath, {
            acceptCallback: deps || (() => {}),
            selfAccepting: true,
          });
        } else {
          // Accepting specific deps
          const callbacks = Array.isArray(deps) ? deps : [deps];
          // Implementation for dep-accepting...
        }
      },
      
      dispose: (callback) => {
        const mod = this.registeredModules.get(ownerPath);
        if (mod) {
          mod.disposeCallback = callback;
        }
      },
      
      invalidate: () => {
        // Force parent to update
        this.socket?.send(JSON.stringify({
          type: 'invalidate',
          path: ownerPath,
        }));
      },
      
      // Access to current module's data
      data: {},
    };
    
    return hot;
  }
}

// Global runtime
const hmr = new HMRRuntime();
hmr.connect(`ws://${location.host}/__hmr`);

// Export for modules
export { hmr };
```

### Building an Error Overlay

```javascript
// ERROR OVERLAY COMPONENT

class ErrorOverlay extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }
  
  static get styles() {
    return `
      :host {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 99999;
        background: rgba(0, 0, 0, 0.85);
        font-family: 'SF Mono', Monaco, Consolas, monospace;
      }
      
      .container {
        max-width: 800px;
        margin: 50px auto;
        padding: 30px;
        background: #1a1a1a;
        border-radius: 8px;
        border: 1px solid #333;
      }
      
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
      }
      
      .title {
        color: #ff5555;
        font-size: 18px;
        font-weight: bold;
      }
      
      .close {
        background: none;
        border: none;
        color: #888;
        cursor: pointer;
        font-size: 24px;
      }
      
      .message {
        color: #ff8888;
        font-size: 16px;
        margin-bottom: 20px;
        white-space: pre-wrap;
      }
      
      .file {
        color: #888;
        margin-bottom: 15px;
      }
      
      .file a {
        color: #4dabf7;
        text-decoration: none;
      }
      
      .code-frame {
        background: #0d0d0d;
        border-radius: 4px;
        padding: 15px;
        overflow-x: auto;
        margin-bottom: 20px;
      }
      
      .line {
        display: flex;
        line-height: 1.6;
      }
      
      .line-number {
        color: #666;
        width: 50px;
        flex-shrink: 0;
        user-select: none;
      }
      
      .line-content {
        color: #ccc;
        white-space: pre;
      }
      
      .line.highlight {
        background: rgba(255, 85, 85, 0.15);
      }
      
      .line.highlight .line-content {
        color: #ff888

…(truncated)
