Vite Importing Assets
Images, fonts, SVGs, videos and other files can be imported from JavaScript in a Vite project. Instead of the file's contents you get back a URL that works in development and points to a hashed, cache-friendly file after the build.
Importing an image
// src/main.js
import logoUrl from './assets/logo.png';
const img = document.createElement('img');
img.src = logoUrl;
document.body.append(img);| Mode | Value of logoUrl |
|---|---|
| Dev | /src/assets/logo.png |
| Build | /assets/logo-BQ3yXq7c.png (hash changes when the file changes) |
| Build, file < 4 KiB | data:image/png;base64,iVBORw0KG... (inlined) |
Because the URL is resolved at build time, a missing or misspelled file is a build error — much better than a broken image in production.
Assets referenced from HTML and CSS
You don't need JavaScript for most assets. Vite also processes URLs found in:
index.html:<img src="./img/hero.jpg">,<link rel="icon" href="...">,<video src>and so on,- CSS:
background: url('./img/pattern.svg'),@font-face { src: url('./fonts/Inter.woff2') }.
/* src/style.css */
@font-face {
font-family: 'Inter';
src: url('./fonts/Inter.woff2') format('woff2');
}
.hero {
background-image: url('./img/hero.jpg');
}After vite build those URLs are rewritten to /assets/Inter-Cx81b2Ld.woff2 and /assets/hero-DkP0aZ1e.jpg.
Content hashing explained
The hash is derived from the file's contents. Same bytes → same name, so browsers can cache the file "forever" (Cache-Control: immutable). Change one pixel → new name → browsers fetch the new file. The playground computes a short content hash the way a bundler might (Vite's real algorithm differs, but the principle is identical):
(async () => {
async function hashName(name, contents) {
const bytes = new TextEncoder().encode(contents);
const digest = await crypto.subtle.digest('SHA-256', bytes);
const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
const dot = name.lastIndexOf('.');
return `${name.slice(0, dot)}-${hex.slice(0, 8)}${name.slice(dot)}`;
}
console.log(await hashName('logo.svg', '<svg>v1</svg>'));
console.log(await hashName('logo.svg', '<svg>v1</svg>'));
console.log(await hashName('logo.svg', '<svg>v2</svg>'));
})();logo-bb27c39a.svg
logo-bb27c39a.svg
logo-0b66dbb6.svg
Note:
crypto.subtlerequires a secure context; if your browser reports an error in this sandbox, the idea is still the same — identical content, identical name.
Import suffixes
Query suffixes change what an import returns:
| Import | You get |
|---|---|
import url from './a.png' |
A URL string (default for known asset types) |
import url from './a.svg?url' |
Force a URL, even for types that would otherwise be processed |
import text from './notes.txt?raw' |
The file contents as a string |
import data from './a.png?inline' |
Always a base64 data: URL |
import url from './a.png?no-inline' |
Never inline, always a separate file |
import Worker from './worker.js?worker' |
A Web Worker constructor |
import init from './lib.wasm?init' |
A function that instantiates a WebAssembly module |
?raw is great for shaders, markdown, or SVG markup you want to inject directly:
import iconSvg from './icons/check.svg?raw';
button.innerHTML = iconSvg + ' Done';Inlining small files
Files smaller than build.assetsInlineLimit (default 4096 bytes) are inlined as base64 data URLs to save a request. Here is what an inlined SVG looks like and that it renders just like a file:
<!doctype html>
<html>
<body style="font-family: system-ui">
<p>An SVG inlined as a data URL (what Vite does for files under 4 KiB):</p>
<img id="logo" width="80" alt="logo">
<pre id="src" style="white-space: pre-wrap; font-size: 12px"></pre>
<script>
const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><circle cx="5" cy="5" r="4" fill="#646cff"/></svg>';
const dataUrl = 'data:image/svg+xml;base64,' + btoa(svg);
document.querySelector('#logo').src = dataUrl;
document.querySelector('#src').textContent = dataUrl;
</script>
</body>
</html>// vite.config.js
export default {
build: {
assetsInlineLimit: 0, // never inline (e.g. for strict CSP rules)
},
};Dynamic URLs with new URL()
For a file whose name is only known at runtime, use the standard new URL(path, import.meta.url) pattern. Vite recognizes it at build time as long as the path is a static string or a simple template literal:
function flagUrl(country) {
return new URL(`./flags/${country}.svg`, import.meta.url).href;
}The URL constructor itself is plain JavaScript — you can see how relative paths resolve against a module URL:
const moduleUrl = 'http://localhost:5173/src/components/Flag.js';
console.log(new URL('./flags/vn.svg', moduleUrl).href);
console.log(new URL('../assets/logo.png', moduleUrl).href);
console.log(new URL('/vite.svg', moduleUrl).href);http://localhost:5173/src/components/flags/vn.svg
http://localhost:5173/src/assets/logo.png
http://localhost:5173/vite.svg
Type declarations for assets
In TypeScript, add /// <reference types="vite/client" /> (the templates put it in src/vite-env.d.ts or in tsconfig.json types). It declares module types for *.png, *.svg, ?raw, ?url and friends so imports type-check.
Tip: Rule of thumb — if your code references the file, put it in
src/and import it. Only files that must keep an exact name and URL (likerobots.txt) belong inpublic/.
Test yourself
What does import logo from './logo.png' give you?
- The image bytes
- A URL string to the image
- An HTMLImageElement
- A Blob
Which suffix imports a file's contents as a string?
- ?url
- ?inline
- ?raw
- ?text
Why are built asset names like logo-BQ3yXq7c.png hashed?
- For security
- So they can be cached long-term and change name whenever content changes
- To hide the original name
- Because servers require it