Static Assets and CSS Handling

Static Assets and CSS Handling in Vite: A museum runs two completely separate ways of putting things in front of visitors.

The Analogy: The Museum Registrar and the Lobby Flyer Rack

A museum runs two completely separate ways of putting things in front of visitors. Behind the scenes a registrar accessions every artwork: each piece is logged, given a unique number derived from the object itself, and every gallery label and catalog entry points at that number. Out in the lobby sits a flyer rack where anyone can drop a printed sheet exactly as it is, with no logging and no number. Your imported assets are the accessioned collection, and the files in public/ are the lobby flyer rack.

The registrar's number is computed from the object, not assigned at random: photograph the same painting twice and you get the same number, alter one brushstroke and the number changes, so the number is a fingerprint of the contents. Because every label references that fingerprint, the museum can prove at a glance whether a wall label still matches the piece behind it, and a coin too small for its own case is simply mounted onto its label card. That fingerprint is the content hash Vite computes from an asset's bytes: logo.svg becomes logo.e696969f.svg, one edited byte makes it logo.ac13bea6.svg, and the smallest assets are inlined straight into the code instead of shipped as separate files.

The lobby rack is the deliberate escape hatch for the few sheets that must keep an exact, predictable title: the visitor map a tour company has pre-printed, or the accreditation notice an inspector fetches by its precise name. These sheets are copied to the lobby verbatim, never renumbered and never fingerprinted, because an outside party has memorized their exact names and a fingerprint suffix would break them. That is the public/ directory: files copied to the output root untouched, referenced by a fixed path, for the cases where a stable name matters more than cache-busting.

The disaster is the flyer whose printed text reads "collection entrance, ground floor, straight ahead," left hanging through the year the whole lobby is relocated behind a construction detour: the sheet is still perfectly correct about the old layout and completely wrong about the building visitors are standing in, so everyone who follows it walks into a wall. That is a hardcoded public path such as /favicon.ico after you deploy under a sub-path like /app/: the reference still points at the domain root, the file it names now lives one segment deeper, and every request 404s, which is the single most common "it worked locally but the deployed site is blank" cause.


Syntax or Core Structure

Importing an asset returns its final URL as a string that Vite tracks. Files in public/ are copied verbatim. CSS is handled with no configuration at all.

// Importing an asset returns its final URL as a string.
import logoUrl from './logo.png'
document.querySelector('img').src = logoUrl

// Query suffixes change what you get back:
import iconUrl from './icon.svg?url'      // always a URL, never inlined
import iconRaw from './icon.svg?raw'      // the file contents as a string
import Worker  from './worker.js?worker'  // a Web Worker constructor

Because the reference is tracked, renaming or deleting the file fails the build loudly instead of shipping a broken link. Assets smaller than build.assetsInlineLimit (default 4096 bytes) are inlined as data URLs; set it to 0 to force every asset to a separate file.

The public/ directory is the escape hatch, copied to the output root with no hashing and no processing.

public/
  favicon.ico
  robots.txt
  manifest.json

Reference public files by a root-absolute path, and compose that path from the base so it survives a sub-path deploy.

<link rel="icon" href="/favicon.ico" />
// Robust against a non-root base such as /app/:
const iconUrl = import.meta.env.BASE_URL + 'favicon.ico'

CSS just works: an import injects it in dev and extracts it to a hashed file in the build. A *.module.css file gets locally scoped, hashed class names, and preprocessors need only their compiler installed.

import './styles/main.css'               // global: injected, then extracted
import styles from './Button.module.css' // scoped: styles.primary is hashed
npm install -D sass   # Vite detects .scss and wires it up, no loader config

Technical Depth: What Gets a Hash and What Ships Verbatim

Two pipelines run side by side. Imported assets are fingerprinted, sometimes inlined, and rewritten to hashed URLs; public/ files are copied byte for byte. Three mechanics decide what a visitor actually downloads.

Inlining below the threshold

Vite compares each imported asset's size against build.assetsInlineLimit. Anything strictly smaller is inlined as a base64 data URL, trading a few bundle bytes for one fewer network request; anything at or above the limit is emitted as its own file. The boundary is a strict less-than, so an asset of exactly 4096 bytes is emitted, not inlined. The model below classifies five assets.

// Vite inlines an asset as a base64 data URL when it is smaller than
// build.assetsInlineLimit (default 4096 bytes); larger or equal assets are
// emitted as separate hashed files. Inlining trades bundle bytes for requests.
const assetsInlineLimit = 4096;

const assets = [
  { name: 'icon.svg',    bytes: 320 },
  { name: 'avatar.webp', bytes: 900 },
  { name: 'sprite.svg',  bytes: 4096 },
  { name: 'logo.png',    bytes: 12048 },
  { name: 'hero.jpg',    bytes: 82000 },
];

let inlined = 0, emitted = 0;
for (const a of assets) {
  const isInlined = a.bytes < assetsInlineLimit;
  if (isInlined) inlined++; else emitted++;
  console.log(
    a.name.padEnd(12) + String(a.bytes).padStart(6) + ' bytes -> ' +
    (isInlined ? 'inlined (data URL)' : 'emitted (separate file)')
  );
}
console.log('inline limit: ' + assetsInlineLimit + ' bytes (strict less-than)');
console.log('inlined: ' + inlined + '  emitted: ' + emitted);
console.log('requests saved by inlining: ' + inlined);

Output:

icon.svg       320 bytes -> inlined (data URL)
avatar.webp    900 bytes -> inlined (data URL)
sprite.svg    4096 bytes -> emitted (separate file)
logo.png     12048 bytes -> emitted (separate file)
hero.jpg     82000 bytes -> emitted (separate file)
inline limit: 4096 bytes (strict less-than)
inlined: 2  emitted: 3
requests saved by inlining: 2

sprite.svg sits exactly on the 4096-byte limit and is emitted, because the comparison is bytes < limit, not <=. Inlining removed two round-trips here, but every inlined byte is duplicated into whatever bundle imports it, so raising the limit to inline large images can bloat the JavaScript that must be parsed before the page can paint.

Content hashing and the reference rewrite

For every emitted asset Vite computes a hash of the file's bytes and folds it into the filename, then rewrites the import specifier in your code to that final name. Because the hash is a pure function of the contents, an unchanged file keeps its name across builds, so returning visitors reuse their cache, and any edit produces a new name, so a stale copy is never served. The model emits two files, then re-emits one after a single-byte change.

// At build time Vite hashes each tracked asset's CONTENT and emits it under a
// hashed filename; the import specifier is rewritten to that final URL. A byte
// change yields a different hash, so browser caches are busted automatically.
const crypto = require('node:crypto');

function hash8(bytes) {
  return crypto.createHash('sha256').update(bytes).digest('hex').slice(0, 8);
}
function emit(name, contents) {
  const dot = name.lastIndexOf('.');
  return name.slice(0, dot) + '.' + hash8(contents) + name.slice(dot);
}

const files = [
  { name: 'logo.svg', contents: '<svg>brand-v1</svg>' },
  { name: 'main.css', contents: '.a{color:red}' },
];

for (const f of files) {
  console.log(f.name + ' -> ' + emit(f.name, f.contents));
}

// Change one byte of logo.svg (v1 -> v2) and re-emit:
console.log('logo.svg (edited) -> ' + emit('logo.svg', '<svg>brand-v2</svg>'));

Output:

logo.svg -> logo.e696969f.svg
main.css -> main.018915ff.css
logo.svg (edited) -> logo.ac13bea6.svg

Editing logo.svg from brand-v1 to brand-v2 changed its hash from e696969f to ac13bea6, so the emitted filename changed and any HTML referencing it now points at the new file. This is why hashed assets can carry a one-year immutable cache header safely: the URL itself changes whenever the bytes do, so a cached copy can never be wrong.

Composing URLs against a non-root base

Vite prepends the configured base to every emitted asset URL automatically, so a bundled import resolves correctly under any deploy path. A public/ asset is different: a literal path you wrote by hand ships exactly as written and does not receive the base prefix, so it must be composed from import.meta.env.BASE_URL. The model resolves the same favicon three ways for base: '/app/'.

// Bundled (imported) assets get their URLs rewritten with the configured base
// automatically. A public/ asset referenced by a hardcoded root path does NOT,
// unless you compose it from import.meta.env.BASE_URL yourself.
const base = '/app/';

function bundledUrl(hashedName) {
  return base + 'assets/' + hashedName;      // Vite prepends base for you
}
function publicHardcoded(path) {
  return path;                                // a literal "/favicon.ico" is left as-is
}
function publicComposed(file) {
  return base + file;                         // import.meta.env.BASE_URL + file
}

console.log('bundled   ./logo.svg          -> ' + bundledUrl('logo.1a2b3c4d.svg'));
console.log('public    href="/favicon.ico" -> ' + publicHardcoded('/favicon.ico'));
console.log('public    BASE_URL+favicon.ico -> ' + publicComposed('favicon.ico'));
console.log('site deploys under ' + base);
console.log('hardcoded ref resolves to domain root, missing the ' + base + ' segment -> 404');

Output:

bundled   ./logo.svg          -> /app/assets/logo.1a2b3c4d.svg
public    href="/favicon.ico" -> /favicon.ico
public    BASE_URL+favicon.ico -> /app/favicon.ico
site deploys under /app/
hardcoded ref resolves to domain root, missing the /app/ segment -> 404
Reference kindWritten in sourceFinal URL when base is /app/
Bundled importimport x from './logo.svg'/app/assets/logo.[hash].svg
Public, hardcodedhref="/favicon.ico"/favicon.ico, 404s under /app/
Public, composedBASE_URL + 'favicon.ico'/app/favicon.ico

Only the middle row is broken, and only under a non-root base. The bundled asset is safe because Vite rewrote its URL, and the composed public reference is safe because you added the base yourself; the hardcoded one points at the wrong origin path and 404s. This is the mechanism behind the blank-deployed-site trap, and it belongs last because it is what actually bites in production.


Real World Example: The Cache-Busting Manifest

Teams that serve assets with long cache lifetimes add a postbuild step that writes a manifest mapping each source asset to its emitted, hashed filename, then a gate that verifies every asset carries a hash before deploy. The model below is that gate: it hashes the tracked assets, builds the manifest, and checks that every entry is cache-bustable.

// A postbuild step writes a manifest mapping each source asset to its emitted,
// content-hashed filename, then verifies every asset is cache-bustable.
const crypto = require('node:crypto');
const hash8 = (b) => crypto.createHash('sha256').update(b).digest('hex').slice(0, 8);

// Assets the BUILD PIPELINE sees (imported from src/). These get hashed.
const tracked = [
  { source: 'src/logo.svg',        contents: '<svg>logo</svg>' },
  { source: 'src/styles/main.css', contents: 'body{margin:0}' },
  { source: 'src/hero.jpg',        contents: 'JPEGDATA-v1' },
];

// Assets in public/ are copied verbatim; the pipeline never imports them, so
// they never enter the manifest at all.
const publicAssets = ['public/og-image.png', 'public/robots.txt'];

// Build the manifest: source path -> emitted, content-hashed name.
const manifest = {};
for (const a of tracked) {
  const dot = a.source.lastIndexOf('.');
  const stem = a.source.slice(a.source.lastIndexOf('/') + 1, dot);
  manifest[a.source] = 'assets/' + stem + '.' + hash8(a.contents) + a.source.slice(dot);
}

// Freshness gate: every asset in the manifest must carry a content hash.
function verifyFresh(m) {
  return Object.values(m).every((name) => /\.[a-f0-9]{8}\./.test(name));
}

for (const [src, out] of Object.entries(manifest)) {
  console.log(src + '  ->  ' + out);
}
console.log('assets in manifest: ' + Object.keys(manifest).length);
console.log('public assets copied verbatim: ' + publicAssets.length + ' (never in manifest)');
console.log('all manifest assets content-hashed? ' + verifyFresh(manifest));
console.log(verifyFresh(manifest) ? 'RESULT: cache-safe' : 'RESULT: unhashed asset found');

Output:

src/logo.svg  ->  assets/logo.54e45343.svg
src/styles/main.css  ->  assets/main.20077037.css
src/hero.jpg  ->  assets/hero.3aa05d0f.jpg
assets in manifest: 3
public assets copied verbatim: 2 (never in manifest)
all manifest assets content-hashed? true
RESULT: cache-safe

The gate does exactly what it was built to do for the assets it can see. All three imported assets receive a content hash in their emitted name, the manifest records the mapping the server will use to set immutable cache headers, and verifyFresh confirms every entry matches the eight-hex-digit pattern, so the build is declared cache-safe.

For those three files the guarantee is real. Edit hero.jpg and its hash changes, the manifest entry changes, the served URL changes, and no visitor is ever handed a stale copy. That is the entire point of content hashing, and the manifest makes it auditable.

But look at the line that prints public assets copied verbatim: 2 (never in manifest). The og-image.png in public/ is referenced by a hardcoded /og-image.png in your HTML, it is copied to the output root with no hash, and because the pipeline never imports it, it never enters manifest. verifyFresh iterates only over Object.values(manifest), so the one asset that genuinely cannot cache-bust is the one asset the check never examines.

That is the design flaw, and it is structural: the gate defines "every asset" as "every asset in the manifest," but the manifest is built only from pipeline-tracked imports, so unhashed public/ files are excluded from the set by construction. The check passes precisely because the risky asset is invisible to it, and a green "cache-safe" becomes evidence for the opposite of what it claims. The durable fix is upstream: keep cache-sensitive assets in src/ so the pipeline hashes them, and reserve public/ for the few files that must keep a fixed name, accepting that those are yours to version by hand.


Common Mistakes

  1. Putting a cache-sensitive asset in public/. Public files are copied unhashed, so browsers keep serving the stale copy until the cache expires; keep such assets in src/ so they are content-hashed.
  2. Hardcoding /favicon.ico and then deploying under a sub-path. The literal path points at the domain root and 404s; compose it from import.meta.env.BASE_URL instead.
  3. Leaving base at / when deploying to a sub-path like example.com/app/. Every emitted asset URL then points at the wrong origin path, the scripts 404, and the page renders blank; set base to the sub-path.
  4. Referencing a public/ file with a relative import. Public assets are not module-graph members, so import './logo.png' aimed at public/ does not resolve; reference them by absolute URL.
  5. Raising assetsInlineLimit to inline large images. Inlined bytes are duplicated into the importing bundle and must be parsed before paint, so large data URLs slow the very load they were meant to speed up.
  6. Assuming an asset of exactly the inline limit is inlined. The comparison is a strict less-than, so a file at exactly 4096 bytes is emitted; only smaller files are inlined.
  7. Using a plain .css file and expecting scoped class names. Only *.module.css files are locally scoped; a regular import is global, so collisions across files are real.
  8. Trusting a manifest-based freshness check to cover everything. It sees only pipeline-tracked assets, so unhashed public/ files pass invisibly; treat it as a backstop, not a proof.
  9. Editing a file in dist/ to fix a stale asset. The next build overwrites it from source, so change the source asset, which re-hashes it, rather than patching the output.

Best Practices

  • Import assets from src/ by default. Let the pipeline track, hash, and cache-bust them, so a byte change always produces a new URL.
  • Reserve public/ for fixed-name files only. Use it for robots.txt, verification files, and anything an external service fetches by an exact URL, and nothing else.
  • Compose public URLs from BASE_URL. Write import.meta.env.BASE_URL + 'file' so references survive a move to a non-root base.
  • Set base to match the deploy path. Decide the sub-path before building, because it is baked into every emitted URL.
  • Serve hashed assets with a long immutable cache. A hashed URL changes whenever the bytes do, so a one-year immutable header is both safe and fast.
  • Prefer *.module.css for component styles. Scoped, hashed class names remove cross-file collisions without naming conventions.
  • Keep assetsInlineLimit near its default. Inline only genuinely tiny assets, and let larger ones stay separate and cacheable.
  • Treat freshness gates as backstops, not guarantees. They see only tracked assets, so keep the risky files out of public/ in the first place.

Practice Exercises

  1. Classify by threshold. Using the inlining model, add a favicon-32.png of 4095 bytes and a banner.png of 4096 bytes. Predict which is inlined and which is emitted, and state the one-line rule that decides it.
  2. Break on a sub-path. Using the base model, set base to /docs/ with a hardcoded <img src="/hero.png"> and a bundled import hero from './hero.png'. Say which one 404s on the deployed site and give the fix.
  3. Explain the hash change. A teammate reports that main.css gets a new filename on some deploys even though "nothing changed." Using the hashing model, give two byte-level changes that would alter the hash, and explain why an unchanged file keeps its name.
  4. Close the manifest blind spot. Extend the manifest model so it also lists public/ assets and flags any that lack a hash. Then explain why the honest fix is to move the asset into src/ rather than to teach the checker about public/.