Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

Gatsby JS- How to properly add an html comment inside head in gatsbyjs?

I followed the instructions on gatsbys website and did the following:

  1. cp .cache/default-html.js src/html.js
  2. went inside the (by gatsby created) html.js file and added a comment in the head section.
  3. instead of I used {/* */} as the first was throwing an error
  4. when i run gatsby develop i first get an error loading /query the 404 page and then other pages as well

Does anyone know how to do that? Thank you.

question from:https://stackoverflow.com/questions/65936739/gatsby-js-how-to-properly-add-an-html-comment-inside-head-in-gatsbyjs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to the docs:

Inserting HTML into the <head>

Anything you render in the html.js component will not be made “live” in the client like other components. If you want to dynamically update your we recommend using React Helmet

So, you can't customize the <head> tag directly with the html.js file. Moreover, Gatsby gets rid off the SSI comments (you can follow the stack trace in this GitHub thread).

Said that. You can try using 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 -->`,
          },
      ]
    }
  }
}

Will output:

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

You an also use one of the APIs that Gatsby exposes to customize the output, onPostBuild should work for you. Copying the html/js then adding custom components (like <ssi-code /> then replacing them using replace-in-file:

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

Source: How to insert SSI comments in Gatsby application?

Additionally, you can, as the thread suggests:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...