Add Favicon with React and Webpack

前端 未结 14 2125
星月不相逢
星月不相逢 2020-12-12 19:46

I am attempting to add a favicon to a React-based website that I made using webpack. It has been a total nightmare to add a favicon and I have tried many solutions to no ava

相关标签:
14条回答
  • 2020-12-12 19:53

    I use favicons-webpack-plugin

    const FaviconsWebpackPlugin = require("favicons-webpack-plugin");
    
    module.exports={
    plugins:[
        new FaviconsWebpackPlugin("./public/favicon.ico"),
    //public is in the root folder in this app. 
    
    ]
    }
    
    0 讨论(0)
  • It's the same as adding any other external script or stylesheet. All you have to do is focus on giving the correct path and rel and type.

    Note: When my favicon image was in the assets folder, it was not displaying the favicon. So I copied the image to the same folder as of my index.html and it worked perfectly as it should.

    <head>
        <link rel="shortcut icon" type="image/png/ico" href="/favicon.png" />
        <title>SITE NAME</title>
    </head>
    

    It worked for me. Hope it works for you too.

    0 讨论(0)
  • 2020-12-12 19:56

    For future googlers: You can also use copy-webpack-plugin and add this to webpack's production config:

    plugins: [
      new CopyWebpackPlugin({ 
        patterns: [ 
         // relative path is from src
         { from: './static/favicon.ico' }, // <- your path to favicon
        ]
     })
    ]
    
    0 讨论(0)
  • 2020-12-12 19:59

    Here is how I did.

    public/index.html

    I have added the generated favicon links.

    ...
    <link rel="icon" type="image/png" sizes="32x32" href="%PUBLIC_URL%/path/to/favicon-32x32.png" />
    <link rel="icon" type="image/png" sizes="16x16" href="%PUBLIC_URL%/path/to/favicon-16x16.png" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/path/to/favicon.ico" type="image/png/ico" />
    

    webpack.config.js

    new HTMLWebpackPlugin({
       template: '/path/to/index.html',
       favicon: '/path/to/favicon.ico',
    })
    

    Note

    I use historyApiFallback in dev mode, but I didn't need to have any extra setup to get the favicon work nor on the server side.

    0 讨论(0)
  • 2020-12-12 20:00
    This worked for me:
    
    Add this in index.html (inside src folder along with favicon.ico)
    
    **<link rel="icon" href="/src/favicon.ico" type="image/x-icon" />**
    
    webpack.config.js is like:
    
     plugins: [new HtmlWebpackPlugin({`enter code here`
            template: './src/index.html'
        })],
    
    0 讨论(0)
  • 2020-12-12 20:02

    Another alternative is

    npm install react-favicon
    

    And in your application you would just do:

       import Favicon from 'react-favicon';
       //other codes
    
        ReactDOM.render(
            <div>
                <Favicon url="/path/to/favicon.ico"/>
                // do other stuff here
            </div>
            , document.querySelector('.react'));
    
    0 讨论(0)
提交回复
热议问题