ViVite · Lesson 3 of 6

Imports & Assets

Vite extends the native ES module system — you can import CSS, images, JSON, SVGs, and more directly from JavaScript. The imports are processed and optimized at build time.

TypeScript
// JavaScript/TypeScript imports — standard
import { useState } from 'react'
import MyComponent from './components/MyComponent'

// CSS imports — injected into the page
import './styles.css'
import './App.module.css'   // CSS Modules

// CSS Modules — locally-scoped class names
import styles from './Button.module.css'
// <button className={styles.button}>Click</button>
// Generates: <button class="Button_button__xyz">

// JSON imports — parsed automatically
import config from './config.json'
console.log(config.apiUrl)   // fully typed!

// Image imports — returns URL string
import logo from './assets/logo.png'
// <img src={logo} alt="Logo" />

// SVG as React component (with @vitejs/plugin-react)
// vite.config.ts: plugins: [react({ include: /.(jsx|tsx|svg)$/ })]
import { ReactComponent as Logo } from './logo.svg'
// <Logo className="logo" />

// SVG as URL
import logoUrl from './logo.svg?url'

// Raw file content (as string)
import shaderSrc from './shader.glsl?raw'
import markdownText from './content.md?raw'

// Dynamic imports — lazy loading
const HeavyComponent = lazy(() => import('./HeavyComponent'))
TypeScript
// Glob imports — import multiple files at once
// import.meta.glob is a Vite-specific API

// Import all markdown posts
const posts = import.meta.glob('./posts/*.md', { eager: true })

// Import all test files
const tests = import.meta.glob('../**/*.test.ts')

// Import all Vue components in a directory
const components = import.meta.glob('./components/**/*.vue', { eager: true })

// Practical use: auto-register Vue components
import { defineAsyncComponent } from 'vue'

const modules = import.meta.glob('./components/**/*.vue')

for (const path in modules) {
  const name = path.split('/').pop()?.replace('.vue', '') ?? ''
  app.component(name, defineAsyncComponent(modules[path]))
}

// Public directory — no processing, served at root URL
// public/favicon.ico → /favicon.ico (in your HTML/CSS)
// public/robots.txt  → /robots.txt
// Don't reference public assets from JS imports — use '/filename.ext'
✦ Tip
Put static assets that need URL references (fonts, icons referenced in CSS) in the `public/` directory. Put assets you import from JavaScript (images in components, SVGs) in `src/assets/`. Vite hashes filenames in `src/assets/` for cache-busting; `public/` filenames are unchanged.