Course contentsShow
← Web Development
Lesson 1375 of 2,98225. Build Tools and BundlersFree lesson

Importing Assets in Vite

How to import CSS, images, fonts, and other static assets in Vite projects.

Importing Assets in Vite

You'll learn how Vite handles CSS files, images, fonts, and other static resources through JavaScript imports.

The Core Idea

In traditional web development, you reference assets through HTML tags or CSS URLs. Vite takes a different approach: you can import assets directly into your JavaScript, just like you'd import modules. Vite then processes these imports, optimizes the files, and gives you the correct URLs to use in production.

Think of it like ordering from a restaurant menu instead of cooking yourself—you tell Vite what asset you need, and it handles all the preparation, optimization, and delivery.

How Asset Imports Work

CSS Files: Import CSS directly in your JavaScript, and Vite injects it into the page:

import './styles.css';

Images: Import images to get optimized URLs:

import logoUrl from './logo.png';
// logoUrl is a string path you can use in img src

Fonts: Reference fonts in CSS as usual, but you can also import them:

import fontUrl from './fonts/custom-font.woff2';

Explicit URL Imports: Add ?url to get just the URL without processing:

import assetUrl from './file.pdf?url';

Raw Content: Use ?raw to import file contents as a string:

import svgContent from './icon.svg?raw';

Why This Matters

Importing assets through JavaScript gives Vite control over optimization. It can hash filenames for cache-busting, compress images, inline small files, and ensure all references update correctly when you build for production.

Key Takeaway: Vite transforms asset imports into optimized URLs and handles bundling automatically—just import what you need like any other JavaScript module.