【问题标题】:How to apply styles to the HTML in Next.js at server side render?如何在服务器端渲染中将样式应用于 Next.js 中的 HTML?
【发布时间】:2021-10-16 21:48:26
【问题描述】:

访问Next.js 并注意网络选项卡中的页面请求。预览不仅显示 HTML,而且显示完全预先设置样式的页面。

当我们使用Styled-ComponentsMaterial-UI 时,它们暴露了ServerStyleSheet,它用于为HTML 中的第一次渲染提供所需的样式。

import { ServerStyleSheet } from 'styled-components'
import { ServerStyleSheets } from '@material-ui/core/styles'

使用react-bootstraptest.css 之类的自定义css 时如何实现相同的输出?

【问题讨论】:

    标签: html css next.js server-side-rendering critical-css


    【解决方案1】:

    您是否关心它是 test.css 还是 React 引导程序 - 为什么不直接内联所有关键样式表?

    可能值得尝试他们的实验性功能

    1. experimental: { optimizeCss: true } 添加到 next.config.js
    2. 安装 critters@0.0.7 作为依赖项

    通过How to inline CSS in the head tag of a NextJS project?

    【讨论】:

      【解决方案2】:

      使用 Tailwind CSS

      https://tailwindcss.com/

      我们可以简单地使用类,它让你的设计变得超级简单

      【讨论】:

      • 嘿阿达什!虽然 Tailwind 是一个很棒且有用的工具,但它实际上并不能解决他的问题。他们想知道如何通过react-bootstrap 或其他样式实现这一目标。
      【解决方案3】:

      在_app文件上添加你的样式文件,你可以在nextjs的pages目录中创建这个文件

      import { AppProps } from "next/app";
      import 'bootstrap/dist/css/bootstrap.min.css';
      import "../your_style.css";
      
      function App({ Component, pageProps }: AppProps) {
        return <Component {...pageProps} />;
      }
      
      
      export default App;
      

      对于 react-bootstrap ,需要添加npm i react-bootstrap bootstrap

      【讨论】:

        【解决方案4】:

        Nextjs 允许您显示 SSG/SSR 页面和禁用 javascript 用户仍然可以看到您的应用,但布局会很混乱 如果你使用 react-bootstrap 组件来构建你的布局。

        在 SSR 中使用 react-bootstrap:

        1. 安装:

          npm i react-bootstrap bootstrap
          
        2. 在您的_app.js 中导入引导样式:

          import 'bootstrap/dist/css/bootstrap.min.css';
          
        3. 然后您可以像在 reactjs 中一样使用您的 react-bootstrap components

        import {Container, Row, Col} from 'react-bootstrap';
                
        const Layout = () => (
          <>
            <Container fluid>
              <Row>
                <Col>
                  <p>Running on Next.js at SSR</p>
                </Col>
              </Row>
            </Container>
          </>
        );
                
        export default Layout;
        

        【讨论】:

          猜你喜欢
          • 2021-06-18
          • 2023-02-01
          • 2020-10-17
          • 1970-01-01
          • 2021-02-07
          • 2021-06-09
          • 1970-01-01
          • 1970-01-01
          • 2020-10-22
          相关资源
          最近更新 更多