无法导入带有样式组件和 Next.js 的 Google 字体

Ram*_*era 2 css reactjs server-side-rendering styled-components next.js

尝试加载 Google 字体时遇到以下问题。我读到我应该写这样的东西_document.js来将它导入到 head 标签中

import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head>
          <link
            rel="preload"
            href="/fonts/noto-sans-v9-latin-regular.woff2"
            as="font"
            crossOrigin=""
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
export default MyDocument;
Run Code Online (Sandbox Code Playgroud)

但这是我必须使用的代码才能使 Styled Components 与 Next.js 一起使用

import Document, { DocumentContext } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:如何修改我的_document.js文件以使用 Google 字体的样式?

另外,如果有任何帮助,这是我正在使用的 GlobalStyle,它不会导入字体

import { createGlobalStyle } from '@xstyled/styled-components';

const GlobalStyle = createGlobalStyle`

@import url('https://fonts.googleapis.com/css2?family=Lato&family=Rubik&display=swap');

* {
    margin: 0;
    padding: 0;
}

*,
*::before,
*::after {
    box-sizing: inherit;
}

html {
    box-sizing: border-box;
    font-size: 62.5%; 
    position: relative;
    background: grey;
}

body {
  font-family: 'Lato', sans-serif;
}
`;

const BasicLayout = ({ children }: { children: any }) => {
  return (
    <>
      <GlobalStyle />
      {children}
    </>
  );
};

export default BasicLayout;
Run Code Online (Sandbox Code Playgroud)

Hoo*_*man 6

前往此页面。

https://nextjs.org/docs/advanced-features/custom-app

请阅读自定义_app.js,然后执行以下操作:

首先,您需要_app.js为您的应用创建自定义。(这必须在您的页面目录的根目录中)

然后需要_app.css在同一个目录下创建

然后将css文件导入到你的 _app.js

import "./_app.css";
Run Code Online (Sandbox Code Playgroud)

然后在您的_app.css文件中,导入您的谷歌字体,如下所示:

@import url("https://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&display=swap");
Run Code Online (Sandbox Code Playgroud)

在 css 文件和 body 标签中添加以下行:

body {
  font-family: "PT Sans Narrow", sans-serif;
  etc..
}
Run Code Online (Sandbox Code Playgroud)