Reputation: 570
I'm working on a Vite project and I struggle to understand the difference between each folder and when to use them for each of my assets.
From Vite Docs about public
:
If you have assets that are:
- Never referenced in source code (e.g. robots.txt)
- Must retain the exact same file name (without hashing)
- ...or you simply don't want to have to import an asset first just to get its URL
Then you can place the asset in a special
public
directory under your project root.
And about assets
:
Referenced assets are included as part of the build assets graph, will get hashed file names, and can be processed by plugins for optimization.
So, if I have an SVG icon that I reference in my source code, it seems it shouldn’t be in public
, since I'm referencing it in the source code.
However, in the official React + Vite example they use icons from both folders:
In App.tsx
:
import reactLogo from './assets/react.svg';
import viteLogo from '/vite.svg';
function App() {
return (
<>
<div>
<a href="https://vitejs.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
</>
);
}
And in index.html
, the icon from the public
folder is referenced again:
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
Given this, is there a practical difference between using public and assets for this case?
What are the best practices for each?
Upvotes: 4
Views: 2730
Reputation: 5494
Well it is quite clear from the Vite folder structure. Since it is a Vite app, they want the Vite logo to be accessible from the public url. As for as React logo is concerned they don't necessarily need to provide a public url. Because you can get the official React logo from the React website.
So if you want other applications on the internet to directly access your images then you need to put those images in the public directory. Also consider putting images in the public folder in the below scenarios:
In all the above scenarios, by putting the images in the public folder you are making sure that your bundle size will not be bloated because of the images.
Upvotes: 0