If you've ever deployed a VitePress site and noticed the browser tab still shows the default VitePress logo, you're not alone. Many developers assume that placing a favicon.ico in the public folder is enough, but VitePress requires a bit more configuration to properly link your icon. This guide walks you through the exact steps to set a custom favicon for your VitePress site, from file placement to verifying the result.
Prerequisites
Before you start, make sure you have:
A VitePress project set up (version 1.x or later).
A favicon file ready. You can use an ICO, PNG, or SVG. If you need to create one, try Mzu favicondl to generate a multi-size favicon.
Basic familiarity with the config.js or config.ts file in your VitePress project.
Step 1: Place Your Favicon File in the Public Directory
VitePress uses Vite under the hood, so static assets should go into the public directory at the root of your project. Files in public are served at the root path and copied to the build output unchanged. For example, if you place favicon.ico in public, it will be accessible at /favicon.ico after building.
Create the public folder if it doesn't exist, and place your favicon file inside. You can also use a PNG or SVG file; just remember the filename.
Note: The public directory is relative to your VitePress project root (where package.json is). If you use the default structure with a docs folder, the public folder should be at the project root, not inside docs.
Step 2: Configure the Favicon in VitePress Config
VitePress allows you to define the <head> tags for your site via the head option in your config file. This is where you add the <link rel="icon"> tag.
Open your .vitepress/config.js (or .ts) and add the following:
This tells VitePress to inject the link tag into the <head> of every page. The href should start with a slash (/) because the file is served from the root.
Step 3: Verify Your Favicon
After configuring, run your development server (npm run docs:dev or yarn docs:dev) and open your site in a browser. Check the tab—your favicon should appear. If it doesn't, try a hard refresh (Ctrl+F5 or Cmd+Shift+R) to bypass cache.
For production, build your site (npm run docs:build) and inspect the generated HTML in .vitepress/dist. Look for your <link rel="icon"> tag in the <head> section.
Common Pitfalls
Incorrect file path: If you place the favicon in docs/public instead of the project root public, it won't be copied. Always use the root public directory.
Missing leading slash: Using href: 'favicon.ico' (without slash) can cause issues on nested routes. Always use /favicon.ico.
Browser caching: Browsers aggressively cache favicons. After updating, clear your cache or use a different filename (e.g., favicon-v2.ico) to force a refresh. For more on cache issues, see our favicon not showing checklist.
SVG support: While SVG favicons are widely supported, some older browsers may not display them. Consider providing a PNG or ICO fallback. Learn more in our SVG favicon guide.
Conclusion
Setting a favicon in VitePress is straightforward once you know where to place the file and how to configure the head tags. By following these steps, you ensure your site has a professional look in browser tabs, bookmarks, and search results. Remember to test in different browsers and clear caches when making changes. For a complete favicon solution, consider using Mzu favicondl to generate all necessary sizes and formats.
設定後、開発サーバー(npm run docs:devまたはyarn docs:dev)を実行し、ブラウザでサイトを開きます。タブを確認すると、faviconが表示されるはずです。表示されない場合は、キャッシュを回避するためにハードリフレッシュ(Ctrl+F5またはCmd+Shift+R)を試してください。
本番環境では、サイトをビルド(npm run docs:build)し、.vitepress/dist内の生成されたHTMLを検査します。<head>セクションに<link rel="icon">タグがあることを確認してください。
VitePress 사이트를 배포한 뒤 브라우저 탭에 여전히 기본 VitePress 로고가 보이는 경험을 해보셨다면, 이는 흔한 일입니다. 많은 개발자가 public 폴더에 favicon.ico를 넣기만 하면 충분하다고 생각하지만, VitePress에서 아이콘을 제대로 연결하려면 추가 설정이 필요합니다. 이 가이드에서는 파일 배치부터 결과 확인까지 VitePress 사이트에 사용자 지정 favicon을 설정하는 정확한 단계를 안내합니다.
사전 준비
시작하기 전에 다음이 준비되어 있는지 확인합니다.
VitePress 프로젝트가 설정되어 있어야 합니다(버전 1.x 이상).
favicon 파일이 준비되어 있어야 합니다. ICO, PNG, SVG 중 하나를 사용할 수 있습니다. 파일을 만들어야 한다면 Mzu favicondl을 사용해 여러 크기의 favicon을 생성해 보세요.
VitePress 프로젝트의 config.js 또는 config.ts 파일에 대한 기본적인 이해가 필요합니다.
1단계: public 디렉터리에 favicon 파일 배치하기
VitePress는 내부적으로 Vite를 사용하므로 정적 자산은 프로젝트 루트의 public 디렉터리에 두어야 합니다. public에 있는 파일은 루트 경로로 제공되며 빌드 출력에 그대로 복사됩니다. 예를 들어 public에 favicon.ico를 두면 빌드 후 /favicon.ico에서 접근할 수 있습니다.
public 폴더가 없다면 생성하고 favicon 파일을 그 안에 넣습니다. PNG나 SVG 파일을 사용해도 되며, 파일 이름만 기억해 두면 됩니다.
이 설정은 VitePress가 모든 페이지의 <head>에 link 태그를 삽입하도록 합니다. href는 파일이 루트에서 제공되므로 슬래시(/)로 시작해야 합니다.
Step 3: Verify Your Favicon
설정 후 개발 서버(npm run docs:dev 또는 yarn docs:dev)를 실행하고 브라우저에서 사이트를 엽니다. 탭을 확인하면 favicon이 표시되어야 합니다. 표시되지 않으면 강력 새로고침(Ctrl+F5 또는 Cmd+Shift+R)으로 캐시를 우회해 보세요.
프로덕션의 경우 사이트를 빌드(npm run docs:build)하고 .vitepress/dist에 생성된 HTML을 검사합니다. <head> 섹션에서 <link rel="icon"> 태그를 찾아보세요.
Common Pitfalls
잘못된 파일 경로: favicon을 프로젝트 루트의 public 대신 docs/public에 두면 복사되지 않습니다. 항상 루트 public 디렉터리를 사용하세요.
선행 슬래시 누락:href: 'favicon.ico'(슬래시 없음)를 사용하면 중첩 라우트에서 문제가 발생할 수 있습니다. 항상 /favicon.ico를 사용하세요.
브라우저 캐싱: 브라우저는 favicon을 적극적으로 캐시합니다. 업데이트 후 캐시를 지우거나 다른 파일명(예: favicon-v2.ico)을 사용하여 새로고침을 강제하세요. 캐시 문제에 대한 자세한 내용은 favicon not showing 체크리스트를 참고하세요.
SVG 지원: SVG favicon은 널리 지원되지만 일부 구형 브라우저에서는 표시되지 않을 수 있습니다. PNG 또는 ICO 대체 파일을 제공하는 것을 고려하세요. 자세한 내용은 SVG favicon 가이드에서 확인하세요.
Conclusion
VitePress에서 favicon을 설정하는 일은 파일을 어디에 두고 head 태그를 어떻게 구성해야 하는지 알기만 하면 간단합니다. 다음 단계를 따르면 브라우저 탭, 북마크, 검색 결과에서 사이트가 전문적인 모습을 갖추게 됩니다. 변경 사항을 적용할 때는 여러 브라우저에서 테스트하고 캐시를 지우는 것을 잊지 마세요. 완전한 favicon 솔루션을 원한다면 Mzu favicondl을 사용해 필요한 모든 크기와 형식을 생성하는 것을 고려해 보세요.
Si alguna vez has desplegado un sitio VitePress y te has dado cuenta de que la pestaña del navegador sigue mostrando el logotipo predeterminado de VitePress, no estás solo. Muchos desarrolladores asumen que basta con colocar un favicon.ico en la carpeta public, pero VitePress requiere un poco más de configuración para enlazar correctamente tu icono. Esta guía te explica los pasos exactos para establecer un favicon personalizado en tu sitio VitePress, desde la colocación del archivo hasta la verificación del resultado.
Requisitos previos
Antes de empezar, asegúrate de tener:
Un proyecto VitePress configurado (versión 1.x o posterior).
Un archivo favicon listo. Puedes usar ICO, PNG o SVG. Si necesitas crear uno, prueba Mzu favicondl para generar un favicon de varios tamaños.
Familiaridad básica con el archivo config.js o config.ts en tu proyecto VitePress.
Paso 1: Coloca tu archivo favicon en el directorio public
VitePress usa Vite internamente, por lo que los recursos estáticos deben ir en el directorio public en la raíz de tu proyecto. Los archivos en public se sirven en la ruta raíz y se copian a la salida de compilación sin cambios. Por ejemplo, si colocas favicon.ico en public, será accesible en /favicon.ico después de la compilación.
Crea la carpeta public si no existe y coloca tu archivo favicon dentro. También puedes usar un archivo PNG o SVG; solo recuerda el nombre del archivo.
Nota: El directorio public es relativo a la raíz de tu proyecto VitePress (donde está package.json). Si usas la estructura predeterminada con una carpeta docs, la carpeta public debe estar en la raíz del proyecto, no dentro de docs.
Paso 2: Configura el favicon en la configuración de VitePress
VitePress te permite definir las etiquetas <head> para tu sitio mediante la opción head en tu archivo de configuración. Aquí es donde agregas la etiqueta <link rel="icon">.
Abre tu .vitepress/config.js (o .ts) y agrega lo siguiente:
Esto le indica a VitePress que inyecte la etiqueta link en el <head> de cada página. El href debe comenzar con una barra (/) porque el archivo se sirve desde la raíz.
Paso 3: Verifica tu favicon
Después de configurar, ejecuta tu servidor de desarrollo (npm run docs:dev o yarn docs:dev) y abre tu sitio en un navegador. Revisa la pestaña: tu favicon debería aparecer. Si no es así, prueba una recarga forzada (Ctrl+F5 o Cmd+Shift+R) para saltar la caché.
Para producción, compila tu sitio (npm run docs:build) e inspecciona el HTML generado en .vitepress/dist. Busca tu etiqueta <link rel="icon"> en la sección <head>.
Errores comunes
Ruta de archivo incorrecta: Si colocas el favicon en docs/public en lugar de la raíz del proyecto public, no se copiará. Usa siempre el directorio raíz public.
Falta la barra inicial: Usar href: 'favicon.ico' (sin barra) puede causar problemas en rutas anidadas. Usa siempre /favicon.ico.
Caché del navegador: Los navegadores almacenan en caché los favicons de forma agresiva. Después de actualizar, borra la caché o usa un nombre de archivo diferente (por ejemplo, favicon-v2.ico) para forzar una actualización. Para más información sobre problemas de caché, consulta nuestra lista de verificación para favicons que no se muestran.
Soporte de SVG: Aunque los favicons SVG son ampliamente compatibles, algunos navegadores antiguos pueden no mostrarlos. Considera proporcionar un fallback PNG o ICO. Aprende más en nuestra guía de favicons SVG.
Conclusión
Configurar un favicon en VitePress es sencillo una vez que sabes dónde colocar el archivo y cómo configurar las etiquetas head. Siguiendo estos pasos, te aseguras de que tu sitio tenga un aspecto profesional en las pestañas del navegador, los marcadores y los resultados de búsqueda. Recuerda probar en diferentes navegadores y borrar la caché cuando hagas cambios. Para una solución completa de favicon, considera usar Mzu favicondl para generar todos los tamaños y formatos necesarios.