FOUC:初始页面已加载,没有任何样式

时间:2020-07-10 13:49:42

标签: javascript reactjs sass next.js fouc

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

但是问题是,页面加载时没有预先应用样式。因此,所有初始页面呈现都会发生哪种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的第3点 它将创建一个静态的散列css文件,并将其附加到<head/>标记中,但问题仍然存在。


我期望什么:

enter image description here

我现在要得到什么:

enter image description here

我没有使用任何外部库,例如“样式组件”等。我也没有在寻找它。

该如何解决当前问题?

1 个答案:

答案 0 :(得分:0)

由于这是JS中的CSS方法,因此文件未在服务器端呈现,无法应用文档预解析器,因此必须等待Javascript下载

  1. 您可以使用Nextjs产品-https://github.com/vercel/styled-jsx-将输出样式服务器以及客户端。
  2. 您可以看看分别导出SCSS并链接到文档头。
  3. 带有节点-sass的下一个-sass输出文件-https://github.com/vercel/next-plugins/tree/master/packages/next-sass + https://github.com/sass/node-sass#outfile