首页 > 解决方案 > 如何在 Gatsby 应用程序中插入 SSI 注释?

问题描述

我正在构建一个 Gatsby 应用程序,我需要插入一些 SSI 行(样式为 HTML 注释)。例子

<!--#set var="section" value="#{section}"-->
<!--#include virtual="/virtual/3.0/script-app.inc"-->

我找不到如何做到这一点。

我需要将这些(和其他脚本)放在标签之前、head标签内、head标签末尾body和紧随其后。

我尝试了很多方法,但没有一个有效。我尝试过更改 html.js,但它只是从输出的代码中删除了注释。我也尝试过使用 gatsby-ssr 和 gatsby-browser,但我一直在想我不知道在这些文档中到底要做什么。

我期望输出是什么(带有示例代码):

<!DOCTYPE html>
    <!--#set var="section" value="#{section}"-->
    <html>
        <head>
             <!--#include virtual="/virtual/3.0/script-app.inc"-->
             [rest of head code]
        </head>
    <body>
</html>

会发生什么:我的输出页面没有任何评论或已将其字符串化(如&lt;!--#include virtual="/virtual/3.0/script-app.inc"--&gt;

标签: reactjsnginxgatsbyssi

解决方案


我使用gatsby-node.jsand解决了这个问题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"-->',
  });

推荐阅读