我正在尝试将 Gatsby 的 Head API 与 Gatsby.js (4.24.2) 和 TypeScript 一起使用,但我得到了一些混合结果。
这是我所拥有的,它可以工作,但某些脚本无法编译:
const Page = ({ location }) => {
// code
return ( ... )
}
export const Head = () => {
return (
<>
<title>Example</title>
<script>console.log("hello")</script>
</>
)
}
这有效,它将页面标题更改为“示例”,并且发送了我的控制台日志。在 VS Code 中,它看起来没有正确格式化控制台日志语句,但无论如何它都可以工作:
(它看起来像纯文本而不是格式化的 JavaScript)
但是,当我尝试像这样向
Head
添加新的自定义 javascript 函数时,Gatsby 不会编译,并且 VS Code 用红色突出显示所有内容,似乎它不知道我正在尝试声明一个函数。
<>
<title>Example</title>
<script>console.log("hello")</script>
<script>(function(w, d, s) { ... script contents })(w,d,s);</script>
</>
谢谢。如果需要可以提供更多信息
我不明白为什么格式不同,但我设法创建了一个可以编译的解决方法,如下所示:
export const Head = () => {
return (
<>
<script dangerouslySetInnerHTML={{
__html: `
console.log("This is the test, and you passed!");
(function(w, d, s) { ... script code ... })(w, d, s);
`
}}/>
</>
)
}