【问题标题】:How can I use next js with ant design library properly with server side rendering?如何在服务器端渲染中正确使用带有 ant 设计库的 next js?
【发布时间】:2021-01-12 05:36:27
【问题描述】:

我用ant design链接克隆了官方的next js示例:https://github.com/vercel/next.js/tree/canary/examples/with-ant-design

然后我做了 npm install 来安装所有依赖项。 然后我做了 npm run dev 看看一切正常。 然后我执行 npm run build 来构建下一个 js 应用程序,然后我运行 npm run start 在 localhost 中运行构建的应用程序。

问题是当我转到网络选项卡并选择 localhost 页面然后从预览选项卡中预览它时,ant 设计实际上并未应用于服务器端渲染,我根本看不到任何样式。 ant design css 需要半秒才能应用,这不是我想要的。

如何正确使用 ant design 和 next js 服务器端渲染?

【问题讨论】:

    标签: javascript next.js ant-design-pro


    【解决方案1】:

    您可能正在寻找内联 CSS,以便浏览器更快地应用它们,而无需先将 CSS 资源作为单独的请求获取。

    有一个关于官方支持的问题,但还没有答案:https://github.com/vercel/next-plugins/issues/364

    但是,有一个解决方法,可以在 https://github.com/vercel/next-plugins/issues/238 中找到,我尝试了这个并且它有效。

    要实现内联 CSS,在pages 文件夹中添加一个名为_document.js 的文件,其内容如下:

    import Document, { Head, Main, NextScript } from 'next/document';
    import fs from 'fs';
    import path from 'path';
    
    class CustomNextHead extends Head {
      // TODO: This might not be needed if Next.js implements built-in support
      // https://github.com/zeit/next-plugins/issues/364
      getCssLinks({ allFiles }) {
        return allFiles
          .filter((file) => file.endsWith('.css'))
          .map((file) => (
            <style
              key={file}
              nonce={this.props.nonce}
              dangerouslySetInnerHTML={{
                __html: fs.readFileSync(path.join('.next', file), 'utf-8'),
              }}
            />
          ));
      }
    }
    
    export default class MyDocument extends Document {
      render() {
        return (
          <html lang="en">
            <CustomNextHead />
            <body>
              <Main />
              <NextScript />
            </body>
          </html>
        );
      }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 2021-03-30
      • 1970-01-01
      • 2021-10-30
      • 2019-04-07
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多