乐闻世界logo
搜索文章和话题

How to add a favicon to a next js static site

1个答案

1

In Next.js, adding a favicon when deploying your application in static mode is a straightforward task. You can achieve this by following these steps:

  1. Prepare Favicon Files: First, prepare one or more favicon files in formats such as .ico, .png, or .svg. While favicon.ico is the most common format due to its compatibility with all browsers, many modern browsers now support other formats like PNG and SVG.

  2. Place Favicon in public Directory: In the root directory of your Next.js project, there is a public directory. Place your favicon file in this directory. Next.js automatically maps resources in the public directory to the root URL of your application.

  3. Update the <Head> Component: In your page components or in the _app.js file, use Next.js's built-in <Head> component to add link tags for the favicon. Typically, this is set globally in pages/_app.js, or it can be set in specific pages at pages/your-page.js.

Here is an example of adding a favicon in pages/_app.js:

jsx
import Head from 'next/head'; function MyApp({ Component, pageProps }) { return ( <> <Head> {/* Add favicon */} <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> <link rel="icon" href="/favicon.ico" type="image/x-icon" /> {/* Support other sizes */} <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" /> <link rel="manifest" href="/site.webmanifest" /> {/* ...other elements if needed (e.g., title, description) ... */} </Head> <Component {...pageProps} /> </> ); } export default MyApp;

In the above example, we add several <link> tags to define icons for different contexts. Modern browsers will select the appropriate icon based on the context.

  1. Build and Deploy: After completing the above steps, when you build and deploy your Next.js application, the favicon will be included automatically and displayed in the browser tab.

Note that if you make these changes in the development environment, you may need to restart the development server to see the new favicon.

2024年6月29日 12:07 回复

你的答案