将 Favicon.ico 添加到 Contentful 或 Gatsby 网站

Adding Favicon.ico to Contentful or Gatsby website

我正在尝试向 Contentful 上的 Gatsby 网站添加新的网站图标徽标。我是将它放在 Contentful 中还是放在 Gatsby 的代码中?话虽如此,有没有办法让 Favicon 也具有动画效果?

I should add, there are not index.html files available unless I make one

index.html 是在您构建站点 (gatsby build) 时创建的,它位于 /public 文件夹下。您应该避免创建或放置自动生成的文件,因为它们将根据放置在 /src 文件夹下的源代码被覆盖。查看Gatsby's folder structure了解更多详情:

  • /public: Automatically generated. The output of the build process will be exposed inside this folder. Should be added to the .gitignore file if not added already.

  • /src: This directory will contain all of the code related to what you will see on the frontend of your site (what you see in the browser), like your site header, or a page template. “src” is a convention for “source code”.

关于网站图标,您可以选择更适合您的选项。

  • 使用gatsby-plugin-manifest(首选方式):只需在您的gatsby-config.js中添加以下配置:

     {
       resolve: `gatsby-plugin-manifest`,
       options: {
         name: `GatsbyJS`,
         short_name: `GatsbyJS`,
         start_url: `/`,
         background_color: `#f7f0eb`,
         theme_color: `#a2466c`,
         display: `standalone`,
         icon: `src/images/icon.png`, 
       },
     },
    

    icon 属性代表网站图标。路径是相对于站点根目录的,必须有效,否则会编译失败。

  • 使用 Contentful:如果您选择该选项,您必须知道必须对网站图标资产进行静态分析。这意味着您需要获取 Contentful 数据才能创建网站图标节点。这种方式将强制您使用 Helmet component 自定义 <header> 标签:

      <Helmet>
        <meta name="icon" href=`${data.edges.nodes.contentfulAssetNode.localFile}` />
      </Helmet>
    

在这种情况下,href 将是 Contentful GraphQL 生成的图标的路径。它应该是本地的,因此 downloadLocal option 应该设置为 true。如果没有进一步的实现细节,就不可能知道您的 GraphQL 结构应该是什么样子。

  • 使用 built-in 解决方案:这可能是前一个,但使用本地路径,如:

      <Helmet>
        <meta name="icon" href=`/favicon.ico` />
      </Helmet>
    

    您可以使用 static folder(在前面的例子中是 /static/favicon.ico)创建有效的 public 路径或直接导入资源,如:

    import favicon from 'path/to/favicon.ico'
    ...
    
      <Helmet>
        <meta name="icon" href={favicon} />
      </Helmet>