React

[Webpack] 웹팩 환경에서 favicon 추가하는 방법

캐럿노트 2024. 11. 15. 19:00

Intro

환경 : React + Webpack

favicon 파일 경로 : src/assets/favicon/favicon.ico

 

HtmlWebpackPlugin을 사용하는 경우

HtmlWebpackPlugin 플러그인을 사용한다면 favicon 경로를 설정하는 것 만으로 간단하게 적용할 수 있다.

다만, 단일 favicon만 처리 가능하다.

  • 장점: 설정이 간단함
  • 장점: 자동으로 favicon을 처리함
  • 단점: 단일 favicon만 처리 가능
// webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
  // ... 다른 설정들
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html",
      favicon: "./src/assets/favicon/favicon.ico"  // favicon 경로 직접 지정
    })
  ]
};

 

파일 로더를 사용하는 경우

  • 장점: 여러 종류의 파일 처리 가능
  • 장점: 출력 경로를 더 유연하게 설정 가능
  • 장점: 다른 이미지 자산들과 함께 일관되게 관리 가능
  • 단점: 설정이 좀 더 복잡함
// webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
  // ... 다른 설정들
  module: {
    rules: [
      // ... 다른 rules
      {
        test: /\.(ico|png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'assets/favicon/[name][ext]'  // 출력 경로 지정
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html"
    })
  ]
};

 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- 첫 번째 방법을 사용할 경우 link 태그 제거 -->
    <!-- 두 번째 방법을 사용할 경우 src 앞에 '/' 추가 -->
    <link rel="favicon" href="/assets/favicon/favicon.ico" />
    <title>경상북도 인구-산업 통합 플랫폼</title>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>