Gatsby 静态查询和渲染 HTML

Gatsby StaticQuery and Rendered HTML

我正在努力了解 <StaticContent> 的行为方式。

如果我在我的应用程序中禁用 javascript,则 <StaticContent> 中的所有内容都不会呈现。 这是预期的行为吗?

有解决办法吗?

部分代码示例:

const Sample = (props: any) => (
  <StaticQuery
    query={graphql`
      query {
        site {
          siteMetadata {
            siteTitle
            siteTitleShort
          }
        }
      }
    `}
    render={(data) => (
      // THIS CODE WILL NOT BE RENDERED IF JAVASCRIPT IS DISABLED
      // YOU'LL NOT BE ABLE TO FIND IT BY LOOKING INTO THE GENERATED HTML FILE.
      <p>{ JSON.stringify(data) }</p>
    )}
  />
);

没那么容易,Gatsby 正在生成应用程序的关键部分,这些部分会在页面加载时显示,然后页面会用 React 重新水化,这意味着它首先会显示关键 HTML 和 CSS 并且仅在此之后加载网站的动态部分。因此,如果您使用一些无法预渲染的额外 React 组件,它们将无法工作,但整个站点应该可以工作。

如果您使用的是服务工作者并从 devtools 禁用了 JS,则可能是缓存问题。尝试从浏览器首选项中禁用 javascript 并在不打开开发工具的情况下从隐身 window 中禁用网站 运行。基于 GatsbyJS 的网站将向您显示一条 <noscript> 消息,因此,回答:

If I disable javascript in my app, everything inside a <StaticContent> will not be rendered. Is this the intended behavior?

当然可以。 Gatsby 是一个基于 React 的框架,因此您需要 JavaScript 启用。

启用 PWA 和服务工作者后,您的网站会更快,使用的数据更少,这确实需要 JavaScript。

从此GitHub thread(您可能会找到一些其他有用的信息):

If you disable Javascript in preferences etc then this does work. The reason this is failing is because when you disable JS in the developer tools it doesn't disable the service worker cache, so Gatsby loads the app shell fallback, which is empty without JS. If you disable JavaScript in your normal (non developer) settings, then the browser will bypass the service worker cache and load the rendered page as expected. To reproduce, go to chrome://settings/content/javascript and disable JS, and your link works.

I think this is fine. The only person likely to disable JavaScript using the developer tools is the site developer themselves. If someone is disabling it for security (or any other non-testing) reason they will use chrome://settings or about:preferences. It works as expected then.

There is a way to workaround it?

不是在ide盖茨比的盒子里,他们提供ide一些SSR(S服务器-Side Rendering) 使其可行的 API(如果您勇敢的话)。 onPreRenderHTML 挂钩 gatsby-ssr.js,就是您要找的东西,尤其是对于 JavaScript 捆绑包,您可能希望使用 getHeadComponents 并过滤掉 JavaScript 捆绑包(或者只是所有脚本标签,并使用 replaceHeadComponents 和过滤后的组件列表。可能需要检查“pre-body components”和“post-body components”

其他有用的资源: