问题描述
我克隆了带有蚂蚁设计链接的官方下一个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中运行所构建的应用程序。
问题是,当我转到网络选项卡并选择本地主机页面,然后从预览选项卡对其进行预览时,该蚂蚁设计实际上并未应用于服务器端渲染,并且根本看不到任何样式。 蚁群设计CSS要花半秒钟的时间,这不是我想要的。
如何在下一个js服务器端渲染中正确使用ant设计?
解决方法
您可能正在寻找的是内联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 {
// 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>
);
}
}