Skip to content

VitePress Asset Handling

VitePress provides two main ways to handle and reference static assets (such as images, stylesheets, fonts, etc.): using the public directory and using relative paths.

Public Directory

The public directory is the ideal place to store static assets that don't need to be processed by the build. These files will be copied verbatim to the final build output root directory.

By default, the public directory is located at docs/public.

Use Cases:

  • Files that need to be accessed via a fixed URL, such as favicon.ico, robots.txt.
  • Assets that won't be directly referenced in Markdown or Vue components.
  • Large images or files that don't need hashing.

How to Reference:

Files stored in the public directory should always be referenced using root absolute paths.

markdown
<!-- Assuming the image is located at docs/public/logo.png -->

![Logo](/logo.png)

Note that the path starts with /, which resolves to the website's root directory.

Relative Path References

You can place asset files (such as images) together with your Markdown files and reference them using relative paths. This is the approach recommended by VitePress (and Vite).

markdown
<!-- Assuming the image is in the same directory as the .md file -->

![An image](./image.png)

How it Works:

When you reference a static asset using a relative path in Markdown or Vue component templates:

  1. The asset will be processed by Vite's build pipeline.
  2. It will be copied to the build output directory (usually dist/assets).
  3. The filename will automatically have a hash appended (for example, image.a41e1e69.png) for long-term caching.
  4. The path referencing the asset will automatically be updated to the correct post-build path.

Advantages:

  • Asset Co-location: You can place images together with the Markdown files that use them, making management easier.
  • Cache Optimization: The hash in the filename ensures that browsers request a new file when the file content changes, otherwise they'll use the cache.

Impact of base Option

If you configured the base option in .vitepress/config.js (for example, when deploying to a subpath on GitHub Pages), VitePress will automatically handle all asset paths correctly.

  • For references to the public directory (such as /logo.png), it will automatically prepend the base value.
  • For relative path references, the build process has already handled all paths, so they will also work correctly.

You don't need to manually add the base prefix to asset paths.

Summary

  • Use public directory: For global resources that need fixed paths and don't participate in the build.
  • Use relative paths: Recommended approach for resources closely related to content, providing better performance and cache control.

Content is for learning and research only.