如何解决生产中未样式化内容的闪烁?

时间:2020-01-15 06:43:59

标签: reactjs next.js fouc

我正在为我的应用程序使用NextJs,并且正在生产中使用FOUC。我不使用样式化的组件,而只是使用模块化的和全局的CSS / SCSS。我认为问题可能出在我的 _document.js 文件

import React from 'react';
import Document, {Html, Head, Main, NextScript} from 'next/document';

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return {...initialProps};
  }

  render() {
    return (
      <Html>
        <Head>
          <link href="/static/scss/vendor/antd.css" rel="stylesheet" />
          <link href="/static/scss/vendor/bootstrap.min.css" rel="stylesheet" />
          <link href="/static/scss/base/typography.css" rel="stylesheet" />
          <link href="/static/scss/base/ionicons.min.css" rel="stylesheet" />
          <link href="/static/scss/base/flaticons.css" rel="stylesheet" />
          <link href="/static/scss/base/reset.css" rel="stylesheet" />
        </Head>
        <body>
          <div id="fb-root" />
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

1 个答案:

答案 0 :(得分:-1)

那是因为您要使用<Link>导入css,因此该应用将呈现,然后浏览器将下载CSS并将其应用。您应该使用next.js插件next-cssnext-Sass,然后按照以下步骤导入CSS:

import "../public/css/myAboveTheFoldCss.css"

Otherwhise this似乎是另一种修复它的方法,但是我建议使用插件。

修改: 如果您使用next-css,则必须将文件导入custom App.js

CSS文件无法导入到_document.js。您可以使用 _app.js或其他任何页面。

因此,您的 pages / _App.js 应该类似于以下内容:

import "../public/css/myAboveTheFoldCss.css"
// import all the css's here

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// MyApp.getInitialProps = async (appContext) => {
//   // calls page's `getInitialProps` and fills `appProps.pageProps`
//   const appProps = await App.getInitialProps(appContext);
//
//   return { ...appProps }
// }

export default MyApp

您还可以使用常规组件,然后将其导入每个页面:
例如 /components/App.js

import Head from 'next/head'
import Header from '../components/Header'
import Footer from '../components/Footer'
import "../public/css/myAboveTheFoldCss.css"
// import all other css files


export default ({children, ...rest }) => ([
  <Head key={0}>
      <meta name='viewport' content='initial-scale=1.0, width=device-width' />
  </Head>,
  <div>
    <Header/>
    {children}
    <Footer />
  </div>
])

然后按如下所示使用它:

import App from '../components/App'
import React from 'react'
class Mycomp extends React.Component {
  constructor (props) {
    super(props)
  }


  render() {
        return(
          <App>
              <p>My component</p>
          </App>
        )
  }
}

export default Mycomp