【问题标题】:FOUC: Initial page loaded without any stylesFOUC:没有任何样式加载的初始页面
【发布时间】:2020-07-10 13:49:42
【问题描述】:

我正在尝试通过为 Nextjs 应用程序导入 _app.js 中的 .scss 文件来应用全局样式。

但问题是,样式并没有在页面加载时预先应用。因此,所有初始页面渲染都会发生 FOUC。

示例 1

以下是上述问题的基本版本:

项目结构:

pages/
    _app.js
    index.js
app.scss
package.json

index.js 文件:

export default function Home() {
  return (
    <div className="hello">
      <p>Hello World</p>
    </div>
  );
}

_app.js 文件:

import "../app.scss";

export default function App({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

app.scss 文件:

 $color: red;

 .hello {
     background-color: lavender;
     padding: 100px;
     text-align: center;
     transition: 100ms ease-in background;

     &:hover {
         color: $color;
     }
 }

package.json 文件:

{
  "name": "basic-css",
  "version": "1.0.0",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "next": "^9.4.5-canary.31", // using canary build as per https://github.com/vercel/next.js/issues/11195
    "node-sass": "4.14.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1"
  },
  "license": "ISC"
}

示例 2 (repo using next-sass)

根据@Ramakay 的answer 的第三点 这会创建一个静态散列 css 文件并将其附加到 &lt;head/&gt; 标签,但问题仍然存在。


我的期望:

我现在得到的:

我没有使用任何外部库,例如“styled-components”等。我也没有在寻找它。

我能做些什么来解决手头的问题?

【问题讨论】:

  • 你有没有解决过这个问题?它仍然存在于当前版本的 NextJS 中。
  • @MatijaMrkaic 我开始使用 styled-components。

标签: javascript reactjs sass next.js fouc


【解决方案1】:

因为这是 JS 中的 CSS 方法,文件不会在服务器端呈现以供文档预解析器应用,因此它必须等待 Javascript 下载

  1. 您可以使用 Nextjs 产品 - https://github.com/vercel/styled-jsx - 将在服务器端和客户端输出样式。
  2. 您可以查看单独导出 SCSS 并链接到文档头。
  3. Next-sass 与 Node-sass 输出文件 - https://github.com/vercel/next-plugins/tree/master/packages/next-sass + https://github.com/sass/node-sass#outfile

【讨论】:

  • 我添加了另一个选项next-sass,它似乎可以随心所欲。我可以看到你使用node-sass,但它应该很容易用next-sass 替换它,根据包文档,它将提取 CSS 并将其链接到你的文档头中。您仍然可以使用 node-sass 来处理它 - 如果是这样,请通过 next.config.js 创建自定义 webpack 配置并使用此处详述的方法 florianbrinkmann.com/en/sass-webpack-4240 希望它有所帮助,选项 3 是我的首选方法。
  • 检查我更新的问题(示例 2)。我也尝试了第三个选项,但它也不起作用。 中存在样式,但它们不会随页面请求一起加载。
  • 正确,我明白了 - 这是一个沙箱 codesandbox.io/s/github/raulsrule/fouc?file=/styles/app.scss(感谢您迄今为止的尝试)您可以看到 H1 的样式未在 html 源上输出 - ce1tm.sse.codesandbox.io 如果您愿意要继续沿着该路径前进,您可以让 node-sass 输出一个 css 文件 - github.com/sass/node-sass#outfile 您可以将其写入磁盘,然后将其链接到文档中。 node-sass 选项可以通过next-sass 接口传递github.com/vercel/next-plugins/tree/master/packages/…
  • 不知何故,我无法按照您在上面最后一条评论中的建议进行操作
  • @boop_the_snoot 你找到解决方案了吗?
猜你喜欢
  • 1970-01-01
  • 2022-08-17
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多