简体   繁体   中英

Next JS v13: How to add font-weight variant of google fonts using @next/font

After Next JS v13, @next/font helps for best performance. Before the package existed, before I used the CDN @import google font in my global CSS

/* path: ./styles/global.css */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800;900&display=swap");

Now I want to migrate and using @next/font@13.0.2

/* path: ./pages/_app.tsx */
import { Poppins } from "@next/font/google";

const poppins = Poppins({
  weight: "800", // I want this font-weight has 400,500,600,700,800,900
});

function MyApp({ Component, pageProps }) {
  return (
    <>
      <style jsx global>{`
        html {
          font-family: ${poppins.style.fontFamily};
        }
      `}</style>

      <Component {...pageProps} />
    </>
  );
}

I've been try to using array instead:

const poppins = Poppins({
  weight: ["400", "500", "600", "700", "800", "900"],
});

but the font used always 400 only

Using CDN on CSS: 在 CSS 上使用 CDN 看起来很正常

Using @next/font@13.0.2 : 使用下一个字体看起来更轻

I want to make the font-weight has 400,500,600,700,800,900 similar like CDN on my CSS. How to make it work and keep it simple? | Expecting an answer on how to use @next/font to add multiple font weights at once.

Thanks

According to the next docs , you can enter "a range of values if it's a variable font such as '100 900'."

Have you tried something like '400 900', to import all of the weights between 400 and 900 for your case? Or you can pass an array of specific font weights you want.

What fixed it for me was adding display: "block", "swap" or "fallback" as the font-display option, because for the default value "optional" the browser was omitting to set the font and/or the font-weight for some reason (perhaps too long loading time or potential layout shift).

// pages/_app.js
import { Nunito } from "@next/font/google";

const nunito = Nunito({
  subsets: ["latin"],
  display: "fallback", // <--
});

But, using "block" obviously could make the site feel less fast, and "swap" / "fallback could cause some noticeable layout shifting, so the default behavior of optionally applying fonts is meant to be beneficial for UX and probably not so crucial for websites with "conventional fonts".

Here are more infos on font-display options

Edit: In my case, the cause of this issue was importing non-modular css (eg import "swiper/css" ) somewhere in a deeply nested component, which applied some font-family and/or font-weight styles which caused this unexpected behavior. If you do this too, try converting the css to a css module .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM