Static Asset Handling
Importing an Asset as URL
Importing a static asset (e.g. an image) will return its URL. For example:
- JavaScript
- TypeScript
import imgUrl from './img.png'
function App() {
return <img src={imgUrl} alt="img" />
}
import imgUrl from './img.png'
function App() {
return <img src={imgUrl} alt="img" />
}
For example, imgUrl
will be /img.png
during development, and become /assets/img.2d8efhg.png
in the production build.
This is what you want to use most of the time, as it ensures that the asset file exists and is included in the bundle.
We are using Vite under the hood, read more about importing static assets in Vite's docs.
The public
Directory
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 the public
directory at the root of your project:
.
└── public
├── favicon.ico
└── robots.txt
Assets in this directory will be served at root path /
during development and copied to the root of the dist directory as-is.
For example, if you have a file favicon.ico
in the public
directory, and your app is hosted at https://myapp.com
, it will be made available at https://myapp.com/favicon.ico
.
Note that:
- You should always reference public assets using root absolute path
- for example,
public/icon.png
should be referenced in source code as/icon.png
.
- for example,
- Assets in the
public
directory cannot be imported from .