====================== Updated docs/advanced/apis to 0.12. (#1729) Updated docs/advanced/middleware-config to 0.12. (#1730) Updated docs/advanced/links to 0.12. (#1732) Updated docs/advanced/web-sockets to 0.12. (#1733) Updated docs/advanced/email to 0.12. (#1734) Auth docs rework (#1723) Updated docs/advanced/jobs to 0.12. (#1740) Updates starter templates (#1744) Updates general docs (#1745) Update customising app docs (#1748) Updates client setup (#1749) Change server config docs (#1750) Updates CSS frameworks docs (#1753) Updates static assets docs (#1751) Updates custom vite config docs (#1754) Update testing docs (#1752) Updated docs/introduction/* to 0.12. (#1756) Restructuring data model docs (#1739) Updates depedencies docs (#1768) Co-authored-by: Mihovil Ilakovac <mihovil@ilakovac.com>
2.0 KiB
title |
---|
Static Asset Handling |
import { ShowForJs, ShowForTs } from '@site/src/components/TsJsHelpers'
Importing an Asset as URL
Importing a static asset (e.g. an image) will return its URL. For example:
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
.
:::info Usage in client code 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 JavaScriptTypeScript. :::