乐闻世界logo
搜索文章和话题

How does Vite handle static assets? How are images, CSS, and other resources loaded?

2月19日 19:16

Vite uses native ES Modules (ESM) to load resources in development environments and bundles and optimizes through Rollup in production. Here's the detailed mechanism of how Vite handles static assets:

Development Environment:

  1. Direct Loading: Static assets are loaded directly via HTTP requests without bundling
  2. Asset References: Control asset loading behavior using suffixes like ?url, ?raw, ?inline
  3. CSS Processing: CSS files are injected via <style> tags, supporting CSS Modules and preprocessors
  4. Image Processing: Images and other assets return URLs, browsers request them directly

Production Environment:

  1. Asset Bundling: Static assets are bundled into the output directory
  2. File Naming: Hash naming (e.g., logo.abc123.png) for long-term caching
  3. Asset References: Asset references in code are replaced with bundled paths
  4. Code Splitting: Dynamically imported assets are split into independent chunks

Asset Type Processing:

Image Assets:

  • Images smaller than 4KB are converted to base64 and inlined by default
  • Large images are output as independent files
  • Supports common formats: png, jpg, jpeg, gif, svg, webp

CSS Assets:

  • Supports preprocessors: CSS, SCSS, SASS, LESS, Stylus
  • Supports CSS Modules
  • Automatically extracts CSS to independent files

JSON Assets:

  • Can import JSON files directly
  • Supports named imports: import { field } from './data.json'

Other Assets:

  • Worker files: Import with ?worker suffix
  • WebAssembly: Import with ?wasm suffix
  • Font files: Direct reference

Asset Reference Methods:

javascript
// Default: Returns URL import logo from './logo.png' // ?raw: Returns string content import content from './file.txt?raw' // ?url: Explicitly returns URL import logoUrl from './logo.png?url' // ?inline: Inline as base64 import logoInline from './logo.png?inline'

Configuration Options:

javascript
export default { build: { assetsInlineLimit: 4096, // Inline threshold (bytes) rollupOptions: { output: { assetFileNames: 'assets/[name]-[hash][extname]' } } }, assetsInclude: ['**/*.glb'] // Custom asset types }

Best Practices:

  1. Place static assets in the public directory, they will be copied directly to the output directory
  2. Use appropriate asset formats (e.g., WebP images)
  3. Configure reasonable inline thresholds
  4. Use CDN to accelerate static asset loading
标签:Vite