如何在服务器端渲染中正确使用带有 ant 设计库的 next js?

我用 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 中运行构建的应用程序。

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

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


胡说叔叔
浏览 170回答 1
1回答

皈依舞

您可能正在寻找的是内联 CSS,以便浏览器更快地应用它们,而无需首先将 CSS 资源作为单独的请求获取。有一个关于官方支持的问题,但还没有答案:https://github.com/vercel/next-plugins/issues/364但是,有一个解决方法,可以在https://github.com/vercel/next-plugins/issues/238中找到,我试过了并且有效。要实现内联CSS,_document.js在pages文件夹中添加一个名为的文件,内容如下:import Document, { Head, Main, NextScript } from 'next/document';import fs from 'fs';import path from 'path';class CustomNextHead extends Head {&nbsp; // TODO: This might not be needed if Next.js implements built-in support&nbsp; // https://github.com/zeit/next-plugins/issues/364&nbsp; getCssLinks({ allFiles }) {&nbsp; &nbsp; return allFiles&nbsp; &nbsp; &nbsp; .filter((file) => file.endsWith('.css'))&nbsp; &nbsp; &nbsp; .map((file) => (&nbsp; &nbsp; &nbsp; &nbsp; <style&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key={file}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nonce={this.props.nonce}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dangerouslySetInnerHTML={{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; __html: fs.readFileSync(path.join('.next', file), 'utf-8'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; ));&nbsp; }}export default class MyDocument extends Document {&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <html>&nbsp; &nbsp; &nbsp; &nbsp; <CustomNextHead />&nbsp; &nbsp; &nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Main />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <NextScript />&nbsp; &nbsp; &nbsp; &nbsp; </body>&nbsp; &nbsp; &nbsp; </html>&nbsp; &nbsp; );&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript