Add Favicon with React and Webpack

前端 未结 14 2126
星月不相逢
星月不相逢 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 20:02

    In my case -- I am running Visual Studio (Professional 2017) in debug mode with webpack 2.4.1 -- it was necessary to put the favicon.ico into the root directory of the project, right where the folder src is rather than in a folder public, even though according to https://create-react-app.dev/docs/using-the-public-folder the latter should be the official location.

    0 讨论(0)
  • 2020-12-12 20:06

    Adding your favicon simply into to the public folder should do. Make sure the favicon is named as favicon.ico.

    0 讨论(0)
  • 2020-12-12 20:07

    Replace the favicon.ico in your public folder with yours, that should get you going.

    0 讨论(0)
  • 2020-12-12 20:12

    The correct answer in the present if you dont use Create React App is the next:

    new HtmlWebpackPlugin({
       favicon: "./public/fav-icon.ico"
    })
    

    If you use CRA then you can modificate the manifest.json in the public directory

    0 讨论(0)
  • 2020-12-12 20:15

    Here is all you need:

    new HtmlWebpackPlugin({
        favicon: "./src/favicon.gif"
    })
    

    That is definitely after adding "favicon.gif" to the folder "src".

    This will transfer the icon to your build folder and include it in your tag like this <link rel="shortcut icon" href="favicon.gif">. This is safer than just importing with copyWebpackPLugin

    0 讨论(0)
  • 2020-12-12 20:15

    Browsers look for your favicon in /favicon.ico, so that's where it needs to be. You can double check if you've positioned it in the correct place by navigating to [address:port]/favicon.ico and seeing if your icon appears.

    In dev mode, you are using historyApiFallback, so will need to configure webpack to explicitly return your icon for that route:

    historyApiFallback: {
        index: '[path/to/index]',
        rewrites: [
            // shows favicon
            { from: /favicon.ico/, to: '[path/to/favicon]' }
        ]
    }
    

    In your server.js file, try explicitly rewriting the url:

    app.configure(function() {
        app.use('/favicon.ico', express.static(__dirname + '[route/to/favicon]'));
    });
    

    (or however your setup prefers to rewrite urls)

    I suggest generating a true .ico file rather than using a .png, since I've found that to be more reliable across browsers.

    0 讨论(0)
提交回复
热议问题