首页 > 解决方案 > Gatsby JS-如何在 gatsbyjs 的头部内正确添加 html 注释?

问题描述

我按照 gatsbys 网站上的说明进行了以下操作:

  1. cp .cache/default-html.js src/html.js
  2. 进入(由 gatsby 创建的)html.js 文件并在 head 部分添加注释。
  3. 而不是我使用 {/* */} 作为第一个抛出错误
  4. 当我运行 gatsby develop 时,我首先收到一个错误,加载/查询 404 页面,然后是其他页面

有谁知道这是怎么做到的吗?谢谢你。

标签: gatsby

解决方案


根据文档

将 HTML 插入到 <head>

您在组件中呈现的任何内容html.js 都不会像其他组件一样在客户端中“活动”。如果你想动态更新你的我们推荐使用React Helmet

因此,您不能直接使用文件自定义<head>标签。html.js此外,Gatsby 摆脱了 SSI 评论(您可以在此 GitHub 线程中跟踪堆栈跟踪)。

这么说的。您可以尝试使用gatsby-plugin-html-comments

module.exports = {
  {
    resolve: `gatsby-plugin-html-comments`,
    options: {
      files: ['./public/**/*.html', './public/*.html'],
      comment: [
        {
          regexp: /<keep-this-comment-tag>(.*?)<\/keep-this-comment-tag>/g,
          comment: `<!-- keep this comment -->`,
          },
      ]
    }
  }
}

将输出:

  <div>
    <!-- keep this comment -->
    <h1>Hello World</h1>
  </div>

您还可以使用 Gatsby 公开的 API 之一来自定义输出,onPostBuild应该适合您。复制html/js然后添加自定义组件(例如<ssi-code />然后使用replace-in-file替换它们:

  replace.sync({
    files: ['./public/**/*.html', './public/*.html'],
    from: /<SSI-before-html>(.*?)<\/SSI-before-html>/g,
    to: '<!--#include virtual="/virtual/example.inc"-->',
  });

资料来源:如何在 Gatsby 应用程序中插入 SSI 评论?

此外,您可以按照线程的建议:

<div dangerouslySetInnerHTML={{ __html: '<!--#set var="section" value="#{section}"-->'}}></div>

推荐阅读