阿里云主机折上折
  • 微信号
Current Site:Index > The quick start mechanism of the development server (Dev Server)

The quick start mechanism of the development server (Dev Server)

Author:Chuan Chen 阅读数:51659人阅读 分类: 构建工具

Vite.js's Dev Server is renowned for its extremely fast startup speed, which is achieved by leveraging native ESM support in modern browsers and a series of optimization strategies. Below are the key implementation principles and specific practices behind its rapid startup mechanism.

Dependency Pre-Bundling and Caching Mechanism

During the first startup, Vite scans project dependencies and uses esbuild to convert CommonJS/UMD modules into ESM format, caching them in the node_modules/.vite directory. Subsequent startups directly reuse the cache, skipping redundant builds:

// vite.config.js
export default {
  optimizeDeps: {
    // Manually specify dependencies that need pre-bundling
    include: ['lodash-es'],
    // Exclude dependencies that don't need pre-bundling
    exclude: ['vue']
  }
}

The pre-bundling phase generates an _metadata.json file to record dependency relationships. When package.json's dependencies remain unchanged, the cache is used directly.

Native ESM Dynamic Import

The browser's direct loading of ESM modules is Vite's core advantage. The development server achieves on-demand compilation by transforming import statements:

<!-- Original code -->
<script type="module">
  import { debounce } from 'lodash-es'
</script>

<!-- Transformed by Vite -->
<script type="module">
  import { debounce } from '/node_modules/.vite/lodash-es.js?v=123456'
</script>

Dynamic imports are appended with query parameters (e.g., ?v=123456) to ensure browser cache updates.

Filesystem Monitoring and HMR Optimization

Vite uses chokidar to monitor file changes but employs intelligent strategies to reduce processing overhead:

  1. Ignore node_modules: Configured via watch: { ignored: '**/node_modules/**' }
  2. Throttling: Uses debounce to consolidate multiple file changes in a short time
  3. Incremental Compilation: Only recompiles changed files and their dependencies

HMR updates are pushed via WebSocket with minimal changes:

// Example HMR message received by the client
{
  type: 'update',
  updates: [
    {
      type: 'js-update',
      path: '/src/components/Button.vue',
      acceptedPath: '/src/components/Button.vue'
    }
  ]
}

Middleware and Request Interception

The development server uses Koa middleware for intelligent request handling:

// Pseudocode: Core Vite middleware logic
app.use(async (ctx, next) => {
  if (isJSRequest(ctx.path)) {
    const file = await transformRequest(ctx.path)
    ctx.type = 'js'
    ctx.body = file.code
  } else {
    await next()
  }
})

Special request types include:

  • /@vite/client: Injects the HMR client script
  • /@fs/*: Accesses files outside the project via absolute paths
  • /?import: Used for dynamic import analysis

Cold Start vs. Hot Start Differences

Startup Phase Cold Start Hot Start
Dependency Handling Full pre-bundling Cache read
Config Loading Full parsing Reuses in-memory config
Port Detection Requires scanning Reuses existing port
Average Time 500ms-2s 50-200ms

Using vite --force forces a cold start, skipping all caches.

Custom Optimization Configurations

Users can further optimize startup speed via configuration:

// vite.config.js
export default {
  server: {
    warmup: {
      // Pre-transform frequently used modules
      clientFiles: ['./src/main.js', './src/App.vue']
    },
    watch: {
      // Adjust watch options
      usePolling: false,
      interval: 100
    }
  }
}

Comparison with Webpack Dev Server

Feature Vite Webpack
Startup Principle Native ESM Bundle
Memory Usage Lower (~200MB) Higher (~1GB)
HMR Speed Instant (1-50ms) Slower (100-1000ms)
Browser Support Modern browsers All browsers
Plugin System Rollup-compatible Webpack ecosystem

Performance Monitoring and Debugging

Use the DEBUG=vite:* environment variable to view detailed startup logs:

DEBUG=vite:* vite

Example log output:

vite:config Using config file at /project/vite.config.js +0ms
vite:deps Hash is consistent. Skipping. +125ms
vite:server Server ready in 247ms. +0ms

Special Handling for Multi-Page Applications

For MPA projects, Vite adopts an on-demand compilation strategy:

// vite.config.js
export default {
  build: {
    rollupOptions: {
      input: {
        main: 'index.html',
        about: 'about.html'
      }
    }
  }
}

Each page entry starts an independent compilation process but shares the same dependency pre-bundling cache.

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.