如何在 Gatsby 体内添加永恒的脚本标签?在正文标签中有条件地呈现脚本?

How to add eternal script tag in Gatsby body ? With conditional rendering of script in body Tag?

例如:-

  const country = "USA" 
    import chat = ('./utils/script'); // script can be imported  from a file
     if(country ="USA")   //  used in component conditionally  
{chat}
else
{ console.log("Not USA")}

告诉我不用 html.js 或 gatsby

你有很多方法可以做到这一点:

如果你需要一些UI逻辑,你可以这样做:

const IndexPage = () => (
  <div>
    <Helmet>
      {country === "USA" && <script src={withPrefix('./utils/script')} type="text/javascript" />
     }
    </Helmet>

  </div>
)
export default IndexPage

关于 withPrefix 的更多详细信息(可能不需要)助手:https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-link/#add-the-path-prefix-to-paths-using-withprefix

您可以通过使用 gatsby-ssr.jsonRenderBody API 以及公开的 setPostBodyComponents 函数来获得相同的结果:

export const onRenderBody = ({ setPostBodyComponents }) => {
  if(country ==="USA"){
    setPostBodyComponents([
        <script src='./utils/script' />,
    ])
  }
}

关于 gatsby-ssr.jsonRenderBody API 的更多详细信息:https://www.gatsbyjs.com/docs/reference/config-files/gatsby-ssr/