Gatsby 站点 - index.js 中的 CSS 在首次访问时未加载

Gatsby site - CSS in index.js doesn't load on first access

我正在构建我的第一个 gatsby 站点,我在部署过程中 运行 遇到了一些 css 问题。

  1. 首先,当我加载 site 时,css 加载 none - 但是当我单击 latest promotions/hktaxi(已完成的页面) 然后 epayment services(链接回 index.js - 与主页相同),css 加载。我最初认为这是一个 netlify 问题,这就是为什么我决定也将它部署到 github 页面 - 但页面在两个平台上看起来完全一样。

  2. 该页面在 Web 上是响应式的,但在移动设备上不是。我已经在线阅读解决方案,认为视口的元标记应该放在我的 html 文件中 - 但是,我没有。我应该创建一个 html.js 文件并在其中插入元标记吗?

将回购放在这里以实现可重复性:github.com/claudiahleung/gatsby-learnings

谢谢!

缺乏实施,但有几分钱和一堆似是而非的原因:

  1. 根据描述的行为,您似乎遇到了一些 hydration 问题。在初始渲染点,none 的样式正在加载或应用,但是当您来回移动(发生再水合的地方)时,它会加载。当您通过直接指向 DOM 而不是 React 的虚拟 DOM (vDOM) 来阻止水合作用时,通常会出现此问题,例如,当请求 windowdocument 在 React 的范围之外(没有钩子)。

    也就是说,这是一个实施问题,而不是 Netlify 或 GitHub 的问题。这应该(而且必须)在本地构建项目时发生,因为最终,Netlify 所做的是在他们的服务器上构建您的项目,并且您应该能够通过 gatsby build && gatsby serve 在本地复制它。如果本地一切按预期工作,您可能会开始考虑 Netlify 问题(通常与环境之间的节点版本不匹配有关)。

    对于你的情况,我很确定你的问题是因为你使用的是样式组件,但你还没有阅读 implementation details in Gatsby's docs because you are missing the required plugins and details in your gatsby-config.js 例如:

    module.exports = {
      plugins: [`gatsby-plugin-styled-components`],
    }
    
  2. 这根本不是真的,您可以 customize the HTML output(因为 Gatsby 允许您这样做)并根据需要操作它,添加所需的元标记(这不是解决方案到你的问题)。只需 运行:

    cp .cache/default-html.js src/html.js
    

    或手动将 default-html.js.cache 文件夹复制到 /src 并将其重命名为 html.js。如果 Gatsby 在编译您的项目时在 /src 文件夹下找到该文件,将使用它作为编译代码的“模板”。它看起来像:

     import React from "react"
     import PropTypes from "prop-types"
    
     export default function HTML(props) {
       return (
         <html {...props.htmlAttributes}>
           <head>
             <meta charSet="utf-8" />
             <meta httpEquiv="x-ua-compatible" content="ie=edge" />
             <meta
               name="viewport"
               content="width=device-width, initial-scale=1, shrink-to-fit=no"
             />
             {props.headComponents}
           </head>
           <body {...props.bodyAttributes}>
             {props.preBodyComponents}
             <div
               key={`body`}
               id="___gatsby"
               dangerouslySetInnerHTML={{ __html: props.body }}
             />
             {props.postBodyComponents}
           </body>
         </html>
       )
     }
    
     HTML.propTypes = {
       htmlAttributes: PropTypes.object,
       headComponents: PropTypes.array,
       bodyAttributes: PropTypes.object,
       preBodyComponents: PropTypes.array,
       body: PropTypes.string,
       postBodyComponents: PropTypes.array,
     }
    

超出问题范围。我建议忽略 .cachepublic 文件夹,将它们添加到 .gitignore 文件中。它们是在每个项目编译中自动生成的,它可能会导致一些 Git 冲突(除非你是唯一的贡献者)但最好不要推送它以避免存储库中的噪音。