TExcelTAD
Home › Vite › Vite public Directory

Vite public Directory

Some files must keep their exact name and URL: robots.txt, favicon.ico, manifest.webmanifest, a _redirects file for your host, or a PDF that other sites link to. Hashing those names would break them. That is what the public/ directory is for.

How public/ works

  • Files in <root>/public/ are served at the site root during development: public/robots.txt → http://localhost:5173/robots.txt.
  • On vite build they are copied unchanged into dist/ — no hashing, no minification, no transformation.
  • You reference them with an absolute path that does not include public.
text
my-app/
├── index.html
├── public/
│   ├── favicon.svg
│   ├── robots.txt
│   └── docs/
│       └── handbook.pdf
└── src/
    └── main.js
html
<!-- index.html -->
<link rel="icon" href="/favicon.svg" />
<a href="/docs/handbook.pdf">Handbook</a>

After the build:

bash · try it yourself
npm run build
find dist -type f | sort
> my-app@0.0.0 build
> vite build

vite v8.3.4 building client environment for production...
✓ 3 modules transformed.
dist/index.html                 0.52 kB │ gzip: 0.33 kB
dist/assets/index-BbF6Ys0x.js   1.12 kB │ gzip: 0.64 kB
✓ built in 64ms
dist/assets/index-BbF6Ys0x.js
dist/docs/handbook.pdf
dist/favicon.svg
dist/index.html
dist/robots.txt

public/ vs. imported assets

public/ Imported from src/
URL Fixed: /robots.txt Hashed: /assets/logo-Dx3k.png
Processing None, copied as-is Can be inlined, optimized, hashed
Missing file Broken link at runtime Build error at build time
Caching Must use short or revalidated caching Can be cached forever (immutable)
Typical files robots.txt, favicon.ico, manifest.webmanifest, CNAME, _headers Images, fonts, SVG icons used by components

Tip: When in doubt, import the file from src/. You get build-time checks and cache-busting for free.

Don't import from public/

A common mistake is writing import logo from '/public/logo.png' or '../public/logo.png'. Vite warns about it because the file would be both copied and bundled. Use the root URL as a plain string instead:

js
// ✅ correct — a string, not an import
const img = document.querySelector('img');
img.src = '/logo.png';

// ❌ warns: files in the public directory are served at the root path
// import logo from '../public/logo.png';

Working with a base path

If your site is deployed under a sub-path (for example https://example.com/my-app/) you set base: '/my-app/' in the config. Vite rewrites URLs it processes, but a string in your JavaScript is just a string. Build the URL with import.meta.env.BASE_URL:

js
const iconUrl = `${import.meta.env.BASE_URL}favicon.svg`;

The playground shows how the same public path turns into the right URL for different base values:

js · try it yourself
function publicUrl(base, file) {
  // BASE_URL always ends with "/"; strip a leading slash from the file
  return base + file.replace(/^\//, '');
}

for (const base of ['/', '/my-app/', './']) {
  console.log(base.padEnd(9), '->', publicUrl(base, '/favicon.svg'));
}
/         -> /favicon.svg
/my-app/  -> /my-app/favicon.svg
./        -> ./favicon.svg

Fetching JSON from public/

Large data files you want to download at runtime (not bundle) also fit well in public/:

js
const res = await fetch(`${import.meta.env.BASE_URL}data/cities.json`);
const cities = await res.json();

The same idea, runnable here with a data: URL standing in for the static file:

js · try it yourself
(async () => {
  const fakeFile = 'data:application/json,' + encodeURIComponent('[{"name":"Hanoi"},{"name":"Da Nang"}]');
  const res = await fetch(fakeFile);
  const cities = await res.json();
  console.log('loaded', cities.length, 'cities:', cities.map((c) => c.name).join(', '));
})();
loaded 2 cities: Hanoi, Da Nang

Changing or disabling the folder

js
// vite.config.js
export default {
  publicDir: 'static',   // use ./static instead of ./public
  // publicDir: false,   // disable the feature entirely
};

Test yourself

You have public/robots.txt. Which URL serves it?

  1. /public/robots.txt
  2. /robots.txt
  3. /assets/robots-abc123.txt
  4. /src/robots.txt

What does Vite do with public/ files during vite build?

  1. Minifies and hashes them
  2. Copies them to dist/ unchanged
  3. Inlines them into the JS bundle
  4. Ignores them

Which file is the best candidate for public/?

  1. A button icon used in a component
  2. A Sass partial
  3. robots.txt
  4. A TypeScript helper