如何将next-js与ant设计库一起正确地用于服务器端渲染



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

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

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

如何将ant设计与下一个js服务器端渲染一起正确使用?

您可能想要的是内联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>
);
}
}

相关内容

最新更新