阿里云主机折上折
  • 微信号
Current Site:Index > The definition and background of the birth of Vite.js

The definition and background of the birth of Vite.js

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

Definition of Vite.js

Vite.js is a modern front-end build tool developed by a team led by Evan You (Yu Yuxi). It leverages the native ES Module (ESM) features, utilizing the browser's built-in support for modularity to achieve extremely fast cold starts and hot updates in the development environment. Unlike traditional bundling tools (e.g., Webpack), Vite.js does not bundle the entire application in development mode but instead compiles and serves source code on demand.

// Example: Typical project structure in Vite.js  
my-vite-project/  
├── node_modules/  
├── public/  
│   └── favicon.ico  
├── src/  
│   ├── assets/  
│   ├── components/  
│   ├── App.vue  
│   └── main.js  
├── index.html  
├── package.json  
└── vite.config.js  

Core features include:

  1. Native ESM Support: Directly uses the browser's native ES module system.
  2. On-Demand Compilation: Only compiles the currently edited file.
  3. Fast HMR: Hot Module Replacement speed is unaffected by project size.
  4. Out-of-the-Box: Built-in support for TypeScript, JSX, CSS preprocessors, etc.

Background of Vite.js

Bottlenecks of Traditional Build Tools

Around 2019-2020, front-end projects grew rapidly in scale, exposing significant performance issues with traditional build tools like Webpack:

  • Cold start time increased linearly with project size.
  • Hot updates required rebuilding the entire dependency graph.
  • High configuration complexity and steep learning curve.
// Webpack configuration example (for comparison)  
const path = require('path');  
module.exports = {  
  entry: './src/index.js',  
  output: {  
    filename: 'bundle.js',  
    path: path.resolve(__dirname, 'dist')  
  },  
  module: {  
    rules: [  
      {  
        test: /\.js$/,  
        exclude: /node_modules/,  
        use: {  
          loader: 'babel-loader'  
        }  
      }  
    ]  
  }  
};  

Evolution of Browser Capabilities

Modern browsers now widely support:

  • ES modules (<script type="module">)
  • Dynamic imports (import())
  • Native CSS variables
  • APIs like Web Workers

These advancements made it possible to bypass the bundling step, which is the foundation of Vite.js's design.

Developer Experience Requirements

Developers' expectations for toolchains have evolved:

  1. Instant Feedback: See changes immediately after saving files.
  2. Low Cognitive Load: Avoid complex build configurations.
  3. Consistency: Ensure consistent behavior between development and production environments.

Breakthroughs in Technology Selection

Vite.js adopts the following technical solutions:

  • Development Server: A lightweight server based on Koa.
  • ESBuild: A blazing-fast JavaScript bundler written in Go.
  • Rollup: An efficient bundling tool for production builds.
// Basic configuration example in vite.config.js  
import { defineConfig } from 'vite'  
import vue from '@vitejs/plugin-vue'  

export default defineConfig({  
  plugins: [vue()],  
  server: {  
    port: 3000,  
    open: true  
  },  
  build: {  
    outDir: 'dist',  
    assetsInlineLimit: 4096  
  }  
})  

Core Design Philosophy

Separation of Development and Production

Vite.js employs entirely different strategies for different environments:

  • Development Mode: On-demand serving based on native ESM.
  • Production Mode: Static asset bundling using Rollup.

Dependency Pre-Bundling

On first startup, it performs:

  1. Scans dependencies in package.json.
  2. Uses ESBuild to convert CommonJS modules to ESM.
  3. Merges small files to reduce the number of requests.
# Pre-bundled cache files  
node_modules/.vite/  
├── _metadata.json  
├── react.js  
├── vue.js  
└── lodash-es.js  

Route-Based Code Splitting

Automatically implements dynamic import code splitting:

// Example of automatic code splitting  
const module = await import('./module.js')  
// Separate chunk files are generated in production  

Ecosystem Adaptation

Framework Support

Vite.js provides official templates for:

  • Vue 3
  • React
  • Preact
  • Lit
  • Svelte
# Command example to create a Vite project  
npm create vite@latest my-project -- --template vue  

Plugin System

Compatible with Rollup's plugin ecosystem while offering Vite-specific APIs:

// Example of a custom plugin  
export default function myPlugin() {  
  return {  
    name: 'transform-file',  
    transform(code, id) {  
      if (id.endsWith('.custom')) {  
        return { code: code.replace('foo', 'bar') }  
      }  
    }  
  }  
}  

Performance Comparison

Benchmark data (based on a project with 1,000 components):

Metric Webpack 5 Vite 2
Cold Start Time 28.6s 1.3s
HMR Update 1.8s 20ms
Memory Usage 1.2GB 300MB

Typical Use Cases

Large Single-Page Applications

Vite is particularly suitable for projects with many components:

  • Component library development
  • Admin systems
  • Complex interactive applications

Prototyping

Quickly validate ideas:

# Start a development server immediately  
npm create vite@latest prototype -- --template react  
cd prototype  
npm install  
npm run dev  

Micro-Frontend Architecture

As a sub-application development tool:

// Configure custom base paths  
export default defineConfig({  
  base: '/micro-app/',  
  build: {  
    manifest: true  
  }  
})  

Technical Implementation Details

Module Resolution Algorithm

Vite extends the browser's native module resolution:

  1. Bare module import rewriting:
    import vue from 'vue'  
    // Transformed to  
    import vue from '/node_modules/.vite/vue.js'  
    
  2. Filesystem caching
  3. Hot update boundary detection

Server Middleware

Key middleware in the development server includes:

  • ESM Transformer: Handles special files like .vue.
  • Source Maps: Generates sourcemaps in real time.
  • Proxy Interception: Handles API request forwarding.
// Example of custom middleware  
export default defineConfig({  
  server: {  
    proxy: {  
      '/api': {  
        target: 'http://localhost:3000',  
        changeOrigin: true  
      }  
    }  
  }  
})  

Production Build Optimizations

While the development environment skips bundling, production builds still use Rollup for:

  • Tree-Shaking: Eliminates unused code.
  • Code Splitting: Automatically splits common modules.
  • Asset Compression: Minimizes JS/CSS/HTML.
// Advanced build configuration  
export default defineConfig({  
  build: {  
    rollupOptions: {  
      output: {  
        manualChunks(id) {  
          if (id.includes('node_modules')) {  
            return 'vendor'  
          }  
        }  
      }  
    }  
  }  
})  

Community Ecosystem Growth

A rich ecosystem has formed around Vite.js:

  • Vitest: A unit testing framework based on Vite.
  • VitePress: A static site generator.
  • Vite Ruby: Ruby on Rails integration.
  • vite-plugin-pwa: PWA support plugin.
// Example using Vitest  
import { test, expect } from 'vitest'  
import { mount } from '@vue/test-utils'  
import Component from './Component.vue'  

test('mounts', () => {  
  const wrapper = mount(Component)  
  expect(wrapper.text()).toContain('Hello')  
})  

Relationship with Other Tools

Comparison with Webpack

Feature Webpack Vite
Dev Mode Bundling Required Not needed
HMR Speed Slow Fast
Config Complexity High Low
Production Build Webpack Rollup

Comparison with Snowpack

Though similar in design philosophy, Vite offers:

  1. More comprehensive framework support.
  2. A more active community.
  3. Tighter integration with the Vue ecosystem.

Version Evolution

Major improvements from v1 to v4:

  • v1: Basic ESM development server.
  • v2: Universal framework support, plugin system.
  • v3: Stability improvements, performance optimizations.
  • v4: Build performance enhancements, higher Node version requirements.
# Command to upgrade Vite  
npm install vite@latest  

In-Depth Configuration Analysis

Common Configuration Examples

export default defineConfig({  
  // Base path  
  base: '/app/',  
    
  // Resolve aliases  
  resolve: {  
    alias: {  
      '@': path.resolve(__dirname, './src')  
    }  
  },  
    
  // CSS handling  
  css: {  
    modules: {  
      localsConvention: 'camelCase'  
    },  
    preprocessorOptions: {  
      scss: {  
        additionalData: `$injectedColor: orange;`  
      }  
    }  
  },  
    
  // Environment variables  
  define: {  
    __APP_VERSION__: JSON.stringify('1.0.0')  
  }  
})  

Environment-Specific Configuration

Supports .env files:

# .env.development  
VITE_API_URL=http://localhost:3000  
// Access in code  
console.log(import.meta.env.VITE_API_URL)  

Advanced Usage Patterns

Multi-Page Applications

export default defineConfig({  
  build: {  
    rollupOptions: {  
      input: {  
        main: path.resolve(__dirname, 'index.html'),  
        admin: path.resolve(__dirname, 'admin.html')  
      }  
    }  
  }  
})  

Custom Middleware

Extend development server functionality:

export default defineConfig({  
  server: {  
    middlewareMode: true,  
    configureServer(server) {  
      server.middlewares.use((req, res, next) => {  
        if (req.url === '/custom') {  
          res.end('Hello from middleware')  
        } else {  
          next()  
        }  
      })  
    }  
  }  
})  

Debugging Tips

Viewing Module Graphs

Add the --debug flag when starting:

vite --debug  

Performance Analysis

Generate build analysis reports:

export default defineConfig({  
  build: {  
    rollupOptions: {  
      output: {  
        manualChunks(id) {  
          if (id.includes('node_modules')) {  
            return 'vendor'  
          }  
        }  
      }  
    }  
  }  
})  

Solutions to Common Issues

Dependency Compatibility Issues

Handling CommonJS modules:

export default defineConfig({  
  optimizeDeps: {  
    include: ['lodash']  
  }  
})  

Path Alias Configuration

Ensure TypeScript also recognizes them:

// tsconfig.json  
{  
  "compilerOptions": {  
    "paths": {  
      "@/*": ["src/*"]  
    }  
  }  
}  

Future Development Directions

The Vite team is exploring:

  1. Smarter Pre-Bundling: Incremental pre-building techniques.
  2. Improved WASM Support: More natural import methods.
  3. Persistent Build Caches: Cross-session cache reuse.
  4. Enhanced SSR Support: Optimizations for server-side rendering.

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.