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:
- Direct Loading: Static assets are loaded directly via HTTP requests without bundling
- Asset References: Control asset loading behavior using suffixes like
?url,?raw,?inline - CSS Processing: CSS files are injected via
<style>tags, supporting CSS Modules and preprocessors - Image Processing: Images and other assets return URLs, browsers request them directly
Production Environment:
- Asset Bundling: Static assets are bundled into the output directory
- File Naming: Hash naming (e.g.,
logo.abc123.png) for long-term caching - Asset References: Asset references in code are replaced with bundled paths
- 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
?workersuffix - WebAssembly: Import with
?wasmsuffix - 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:
javascriptexport default { build: { assetsInlineLimit: 4096, // Inline threshold (bytes) rollupOptions: { output: { assetFileNames: 'assets/[name]-[hash][extname]' } } }, assetsInclude: ['**/*.glb'] // Custom asset types }
Best Practices:
- Place static assets in the
publicdirectory, they will be copied directly to the output directory - Use appropriate asset formats (e.g., WebP images)
- Configure reasonable inline thresholds
- Use CDN to accelerate static asset loading