You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gatsby项目中SyntaxError: Unexpected token '<'错误原因及修复

错误原因
  • 嵌套<script>引发解析错误:你在type="text/partytown"的script标签里,用dangerouslySetInnerHTML嵌套了另一层<script>标签。Partytown会把这段内容当作JS代码解析,<属于HTML语法,在JS里是非法字符,直接触发了Unexpected token '<'错误。
  • 字符串未闭合:FreshChat的token值"3456d-e81e-4201-b9ac-324efdvsffda,少了末尾的双引号,这也会导致JS语法不完整,加重解析问题。
修复代码

把gatsby-ssr.js改成下面这样:

import * as React from 'react'
import { Partytown } from '@builder.io/partytown/react'

export function onRenderBody({ setHeadComponents, setPreBodyComponents, setHtmlAttributes }) {
    setHtmlAttributes({ lang: 'en' })
    setHeadComponents([
        <Partytown key="partytown" debug={true} forward={['dataLayer.push']} />,
        <script
            type="text/partytown"
            dangerouslySetInnerHTML={{
                __html: `function initFreshChat() {
                    window.fcWidget.init({
                        token: "3456d-e81e-4201-b9ac-324efdvsffda",
                        host: "https://wchat.eu.freshchat.com"
                    });
                }
                function initialize(i,t){var e;i.getElementById(t)?initFreshChat():((e=i.createElement("script")).id=t,e.async=!0,e.src="https://wchat.freshchat.com/js/widget.js",e.onload=initFreshChat,i.head.appendChild(e))}function initiateCall(){initialize(document,"freshchat-js-sdk")}window.addEventListener?window.addEventListener("load",initiateCall,!1):window.attachEvent("load",initiateCall,!1);`
            }}
        />,
    ])
    // 可选:禁用JS时的备用内容
    setPreBodyComponents([])
}
修复要点
  1. 删掉__html里的<script>和</script>标签,只保留纯JS代码,Partytown才能正确解析执行。
  2. 补全token值末尾的双引号,修复字符串未闭合的语法错误。
  3. 清理多余的空白缩进,保持代码整洁。

内容的提问来源于stack exchange,提问作者Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:01:19