Static Asset Handling
What you'll learn: How to import and use images, fonts, and other files directly in your React components with Vite handling the optimization automatically.
The Asset Problem
In traditional web development, you'd reference images with relative paths like <img src="./logo.png"> and hope the file is in the right folder when deployed. With modern tooling, we can do better—treating assets as imports that the build system tracks and optimizes.
How Vite Handles Assets
When you import an asset in React, Vite automatically:
- Tracks the dependency so the file is included in your build
- Optimizes the file (compression, format conversion)
- Generates a unique URL with a hash (for cache busting)
- Returns the production-ready path you can use directly
Think of Vite as a smart librarian: instead of you remembering where every book is shelved, you just ask for it by name, and the librarian hands you the exact copy, properly cataloged and ready to use.
Using Assets in JSX
import logo from './assets/logo.png'
function Header() {
return <img src={logo} alt="Logo" />
}
The logo variable now contains something like "/assets/logo-a3b4c5d6.png" in production—a versioned URL Vite generated. You can also import CSS files, JSON data, or fonts the same way.
For files in the public/ folder, use absolute paths like <img src="/favicon.ico">. These files are served as-is without processing.
Key Takeaway: Importing assets directly in JSX lets Vite bundle, optimize, and version them automatically—your code references them safely, and the build system handles the rest.