If you've ever built a Webpack project and noticed the browser tab shows a generic globe or a blank square, you're not alone. Webpack doesn't handle favicons out of the box — you need to wire it up yourself. The good news: it's a few lines of config once you know where to put the file and how to inject the link tag.
This guide walks you through adding a favicon to a Webpack project, from placing the file to verifying it in the browser. We'll cover both the simple copy approach and the HtmlWebpackPlugin method, plus the pitfalls that trip up most developers.
Prerequisites
You should have a working Webpack project with webpack and webpack-cli installed. If you're using html-webpack-plugin to generate your HTML, that's even better — we'll use it in the recommended approach. A favicon file (ICO, PNG, or SVG) ready to go. If you need one, you can generate a multi-size ICO with our guide.
Step 1: Place the favicon in your project
Create a folder for static assets if you don't have one. A common convention is src/assets/ or public/. Put your favicon file there — let's call it favicon.ico for maximum browser compatibility. You can also use favicon.png or favicon.svg; SVG is supported in modern browsers but needs a fallback for older ones (see SVG with PNG fallback).
For this guide, we'll assume the file is at src/assets/favicon.ico.
Step 2: Configure Webpack to copy the favicon
Webpack needs to know about the file so it ends up in your build output. The simplest way is to use copy-webpack-plugin. Install it:
npm install --save-dev copy-webpack-plugin
Then add it to your webpack.config.js:
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
// ... other config
plugins: [
new CopyPlugin({
patterns: [
{ from: 'src/assets/favicon.ico', to: 'favicon.ico' }
]
})
]
};
This copies the favicon to the root of your output directory (e.g., dist/favicon.ico). Browsers automatically request /favicon.ico if no link tag is present, so this alone can work — but explicit link tags are better for control and for non-ICO formats.
Step 3: Inject the link tag with HtmlWebpackPlugin
If you're using html-webpack-plugin, you can add the favicon link directly in your HTML template. In your index.html template (usually in src/), add this inside the <head>:
Because the file is copied to the output root, the relative path favicon.ico resolves correctly. If you're serving from a subdirectory, use an absolute path like /favicon.ico or configure publicPath in Webpack.
The rel='icon' attribute is defined in the HTML standard as the way to specify a site icon. Browsers use it to pick the best icon for tabs, bookmarks, and history.
Step 4: Build and verify
Run your build command (e.g., npm run build). Check that favicon.ico appears in your output folder. Then serve the build locally (e.g., with npx serve dist) and open it in a browser. The tab should show your icon. If it doesn't, hard-refresh (Ctrl+Shift+R or Cmd+Shift+R) to bypass cache.
You can also inspect the page source to confirm the link tag is present and the path is correct.
Common pitfalls
Wrong output path: If you use CopyPlugin with a to path that includes a subfolder, the link tag must match. For example, to: 'assets/favicon.ico' requires href='assets/favicon.ico'.
Missing file in production: Some setups only copy assets during development. Ensure CopyPlugin runs in all modes.
Cache issues: Browsers cache favicons aggressively. Use a query string like favicon.ico?v=2 when updating, or configure cache-busting in your build (see cache busting best practices).
SVG without fallback: Older browsers ignore SVG favicons. Always include an ICO or PNG fallback.
File not at root: If you don't use a link tag and rely on the default /favicon.ico request, the file must be at the root of your served directory.
Conclusion
Adding a favicon to a Webpack project is straightforward once you know the two key pieces: copying the file to the output and referencing it in your HTML. Use copy-webpack-plugin to move the asset, and add a link rel='icon' tag in your template. That's it — your tabs will look polished and professional.
If you need to generate a complete favicon set (ICO, PNG, Apple Touch, manifest icons), try Mzu favicondl to create all the files in one go.
如果你做过 Webpack 项目,又发现浏览器标签页里只有一个通用地球图标或空白方块,这并不少见。Webpack 不会开箱即用地处理 favicon,需要你自己接入。好在弄清文件放在哪里、再注入 link 标签后,只需几行配置就能搞定。
ビルドコマンドを実行します(例:npm run build)。出力フォルダーにfavicon.icoが配置されているか確認します。次に、ビルド結果をローカルで配信して(例:npx serve dist)、ブラウザで開きます。タブにはアイコンが表示されるはずです。表示されない場合は、キャッシュを回避するためハードリロード(Ctrl+Shift+RまたはCmd+Shift+R)を行ってください。
Webpack 프로젝트를 만들어 본 적이 있고 브라우저 탭에 기본적인 지구 아이콘이나 빈 사각형이 표시되는 것을 발견했다면, 여러분만 겪은 일은 아닙니다. Webpack은 기본적으로 favicon을 처리하지 않기 때문에 직접 연결해야 합니다. 파일을 어디에 두고 link tag를 어떻게 삽입하는지 알면 설정은 몇 줄이면 충분합니다.
이 가이드는 favicon 파일을 프로젝트에 배치하는 것부터 브라우저에서 확인하는 것까지, Webpack 프로젝트에 favicon을 추가하는 방법을 안내합니다. 간단한 copy 방식과 HtmlWebpackPlugin 방식, 그리고 대부분의 개발자가 빠지기 쉬운 함정까지 다룹니다.
사전 준비 사항
Webpack과 webpack-cli가 설치된 정상 동작하는 Webpack 프로젝트가 필요합니다. HTML을 생성하기 위해 html-webpack-plugin을 사용하고 있다면 더 좋습니다. 권장하는 방식에서는 이 plugin을 사용합니다. 바로 사용할 준비가 된 favicon 파일(ICO, PNG 또는 SVG)이 필요합니다. favicon 파일이 필요하다면 multi-size ICO 생성 가이드를 참고하세요.
1단계: 프로젝트에 favicon 배치하기
static assets를 위한 폴더가 없다면 하나 만드세요. 일반적으로 사용하는 위치는 src/assets/ 또는 public/입니다. favicon 파일을 그곳에 넣으세요. 브라우저 호환성을 최대한 확보하기 위해 여기서는 favicon.ico라고 부르겠습니다. favicon.png이나 favicon.svg도 사용할 수 있습니다. SVG는 최신 browser에서 지원되지만 구형 browser에는 fallback이 필요합니다(PNG fallback을 적용한 SVG).
이 가이드에서는 파일이 src/assets/favicon.ico에 있다고 가정합니다.
2단계: Webpack이 favicon을 복사하도록 설정하기
Webpack이 해당 파일을 처리하여 build output에 포함되도록 해야 합니다. 가장 간단한 방법은 copy-webpack-plugin을 사용하는 것입니다. 다음과 같이 설치하세요:
npm install --save-dev copy-webpack-plugin
그런 다음 webpack.config.js에 다음과 같이 추가합니다:
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
// ... other config
plugins: [
new CopyPlugin({
patterns: [
{ from: 'src/assets/favicon.ico', to: 'favicon.ico' }
]
})
]
};
이 과정은 favicon을 출력 디렉터리의 루트에 복사합니다(예: dist/favicon.ico). link 태그가 없으면 브라우저가 자동으로 /favicon.ico를 요청하므로 이것만으로도 작동할 수 있습니다. 다만 제어하거나 ICO가 아닌 형식을 사용하려면 명시적인 link 태그가 더 좋습니다.
3단계: HtmlWebpackPlugin으로 link 태그 주입
html-webpack-plugin을 사용한다면 HTML 템플릿에 favicon link를 직접 추가할 수 있습니다. index.html 템플릿(일반적으로 src/에 있음)의 <head> 안에 다음을 추가하세요:
rel='icon' 속성은 사이트 아이콘을 지정하는 방법으로 HTML 표준에 정의되어 있습니다. 브라우저는 이 속성을 사용해 탭, 북마크, 기록에 가장 적합한 아이콘을 선택합니다.
4단계: 빌드 및 확인
빌드 명령을 실행하세요(예: npm run build). 출력 폴더에 favicon.ico가 나타나는지 확인합니다. 그런 다음 빌드 결과를 로컬에서 서빙하고(예: npx serve dist) 브라우저에서 열어 보세요. 탭에 아이콘이 표시되어야 합니다. 표시되지 않으면 캐시를 우회하도록 hard-refresh(Ctrl+Shift+R 또는 Cmd+Shift+R)를 하세요.
페이지 소스를 확인해 link 태그가 존재하는지, 경로가 올바른지 확인할 수도 있습니다.
자주 발생하는 문제
잘못된 output path:CopyPlugin의 to 경로에 하위 폴더를 포함했다면 link tag도 일치해야 합니다. 예를 들어 to: 'assets/favicon.ico'를 사용하는 경우 href='assets/favicon.ico'가 필요합니다.
Production에서 파일이 누락됨: 일부 설정에서는 개발 중일 때만 asset을 복사합니다. 모든 모드에서 CopyPlugin이 실행되도록 설정해야 합니다.
캐시 문제: 브라우저는 favicon을 강하게 캐시합니다. favicon을 업데이트할 때는 favicon.ico?v=2와 같은 query string을 사용하거나 build에 cache busting을 설정하세요(cache busting 모범 사례 참고).
fallback 없는 SVG: 구형 브라우저는 SVG favicon을 무시합니다. 항상 ICO 또는 PNG fallback을 포함해야 합니다.
파일이 루트에 없음: link tag를 사용하지 않고 기본 /favicon.ico 요청에 의존한다면 파일이 서비스되는 디렉터리의 루트에 있어야 합니다.
결론
Webpack 프로젝트에 favicon을 추가하는 일은 핵심 두 가지를 알면 간단합니다. 파일을 output에 복사하고 HTML에서 참조하면 됩니다. copy-webpack-plugin으로 asset을 옮기고 템플릿에 link rel='icon' tag를 추가하세요. 그뿐입니다. 브라우저 탭이 다듬어진 professionally한 디자인을 갖게 됩니다.
완전한 favicon 세트(ICO, PNG, Apple Touch, manifest icons)를 생성해야 한다면 Mzu favicondl을 사용해 필요한 파일을 한 번에 만들어 보세요.
Si alguna vez has creado un proyecto con Webpack y has visto que la pestaña del navegador muestra un globo genérico o un cuadrado en blanco, no eres el único. Webpack no gestiona los favicons de forma nativa: tendrás que conectarlo tú. La buena noticia es que solo necesitas unas líneas de configuración cuando sabes dónde colocar el archivo y cómo insertar el link tag.
En esta guía te explicamos cómo añadir un favicon a un proyecto de Webpack, desde colocar el archivo hasta comprobarlo en el navegador. Veremos tanto el enfoque sencillo de copia como el método con HtmlWebpackPlugin, además de las trampas que hacen tropezar a la mayoría de los desarrolladores.
Requisitos previos
Deberías tener un proyecto de Webpack funcionando con webpack y webpack-cli instalados. Si utilizas html-webpack-plugin para generar tu HTML, mejor todavía: lo usaremos en el enfoque recomendado. También necesitarás un archivo favicon (ICO, PNG o SVG) listo para usar. Si no tienes uno, puedes generar un ICO de varios tamaños con nuestra guía.
Paso 1: Coloca el favicon en tu proyecto
Crea una carpeta para los assets estáticos si aún no tienes una. Una convención habitual es src/assets/ o public/. Coloca allí tu archivo favicon; puedes llamarlo favicon.ico para lograr la máxima compatibilidad con los navegadores. También puedes usar favicon.png o favicon.svg; los navegadores modernos admiten SVG, pero necesita un fallback para los más antiguos (consulta SVG con fallback PNG).
En esta guía, supondremos que el archivo está en src/assets/favicon.ico.
Paso 2: Configura Webpack para copiar el favicon
Webpack debe conocer el archivo para que termine en el directorio de salida de tu build. La forma más sencilla de hacerlo es utilizar copy-webpack-plugin. Instálalo:
npm install --save-dev copy-webpack-plugin
Después, añádelo a tu webpack.config.js:
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
// ... other config
plugins: [
new CopyPlugin({
patterns: [
{ from: 'src/assets/favicon.ico', to: 'favicon.ico' }
]
})
]
};
Esto copia el favicon a la raíz de tu directorio de salida (p. ej., dist/favicon.ico). Los navegadores solicitan automáticamente /favicon.ico si no hay una etiqueta link, por lo que esto puede ser suficiente; sin embargo, las etiquetas link explícitas son mejores porque te ofrecen más control y permiten usar formatos que no sean ICO.
Paso 3: Inyecta la etiqueta link con HtmlWebpackPlugin
Si usas html-webpack-plugin, puedes añadir el enlace al favicon directamente en tu plantilla HTML. En tu plantilla index.html (normalmente en src/), añade esto dentro de <head>:
Como el archivo se copia a la raíz de salida, la ruta relativa favicon.ico se resuelve correctamente. Si sirves el sitio desde un subdirectorio, utiliza una ruta absoluta como /favicon.ico o configura publicPath en Webpack.
El atributo rel='icon' está definido en el estándar HTML como la forma de especificar el icono de un sitio. Los navegadores lo utilizan para elegir el icono más adecuado para las pestañas, los marcadores y el historial.
Paso 4: Compila y verifica
Ejecuta tu comando de compilación (p. ej., npm run build). Comprueba que favicon.ico aparezca en la carpeta de salida. Después, sirve la compilación localmente (p. ej., con npx serve dist) y ábrela en un navegador. La pestaña debería mostrar tu icono. Si no lo hace, haz una recarga forzada (Ctrl+Shift+R o Cmd+Shift+R) para omitir la caché.
También puedes inspeccionar el código fuente de la página para confirmar que la etiqueta link está presente y que la ruta es correcta.
Problemas habituales
Ruta de salida incorrecta: Si usas CopyPlugin con una ruta to que incluya una subcarpeta, la etiqueta link debe coincidir con ella. Por ejemplo, to: 'assets/favicon.ico' requiere href='assets/favicon.ico'.
Archivo ausente en producción: Algunas configuraciones solo copian los assets durante el desarrollo. Asegúrate de que CopyPlugin se ejecute en todos los modos.
Problemas de caché: Los navegadores guardan los favicons en caché de forma agresiva. Usa una query string como favicon.ico?v=2 al actualizarlo, o configura cache busting en tu build (consulta las buenas prácticas de cache busting).
SVG sin fallback: Los navegadores más antiguos ignoran los favicons SVG. Incluye siempre un fallback ICO o PNG.
Archivo no está en la raíz: Si no usas una etiqueta link y dependes de la solicitud predeterminada de /favicon.ico, el archivo debe estar en la raíz del directorio que sirves.
Conclusión
Añadir un favicon a un proyecto Webpack es sencillo una vez que conoces los dos elementos clave: copiar el archivo a la salida y referenciarlo en tu HTML. Usa copy-webpack-plugin para mover el asset y añade una etiqueta link rel='icon' en tu template. Eso es todo: tus pestañas se verán pulidas y profesionales.
Si necesitas generar un conjunto completo de favicons (ICO, PNG, Apple Touch, manifest icons), prueba Mzu favicondl para crear todos los archivos de una sola vez.
Generate Your Favicon Set
Create ICO, PNG, SVG, and Apple Touch icons in seconds with Mzu favicondl. No design skills needed.