gpt4 book ai didi

reactjs - 使用 next.js 和样式组件重新加载时无样式文本 (FOUT) 的 Flash

转载 作者:行者123 更新时间:2023-12-04 04:27:34 24 4
gpt4 key购买 nike

我正在使用 next.js 样式组件的全局样式,每次我重新加载我的页面时,我都能看到字体闪烁。

font flash

我的字体文件在 public/fonts/Inconsolata
我在频谱聊天中到处寻找,next.js github问题,但似乎找不到任何解决方案。

页面/index.js

import styled from 'styled-components';

const H1 = styled.h1`
font-family: 'Inconsolata Bold';
font-weight: 700;
color: #000;
`;

const index = () => {
return (
<div>
<H1>font flashes</H1>
</div>
);
};

export default index;

页面/_app.js
import App from 'next/app';
import React from 'react';

import GlobalStyle from '../src/style/globalStyle';

export default class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<>
<GlobalStyle />
<Component {...pageProps} />
</>
);
}
}


pages/_document.js
import Document from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
static async getInitialProps(ctx) {
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();
}
}
}

样式/globalStyle.js
import { createGlobalStyle } from 'styled-components';

const globalStyle = createGlobalStyle`
@font-face {
font-family: 'Inconsolata';
src: url('./fonts/Inconsolata/Inconsolata-Regular.woff2') format('woff2'),
url('./fonts/Inconsolata/Inconsolata-Regular.woff') format('woff');
font-weight: 400;
font-style: normal;
font-display: fallback;
}
@font-face {
font-family: 'Inconsolata Bold';
src: url('./fonts/Inconsolata/Inconsolata-Bold.woff2') format('woff2'),
url('./fonts/Inconsolata/Inconsolata-Bold.woff') format('woff');
font-weight: 700;
font-style: bold;
font-display: fallback;
}
`;

export default globalStyle;

最佳答案

更新:
Next.js 发布了一个名为 的新功能Automatic Webfont Optimization .
只需包含您的字体(目前仅适用于 Google 字体),它将在构建时作为原始 css 包含在内。

// Before
<link
href="https://fonts.googleapis.com/css2?family=Inter"
rel="stylesheet"
/>

// After
<style data-href="https://fonts.googleapis.com/css2?family=Inter">
@font-face{font-family:'Inter';font-style:normal.....
</style>

查看 Next.js 人员如何在他们的网站上处理它,该网站是开源的,可以在 here 上找到。 .检查一下,它对我有用。
  • 通过预加载链接在 css @font-face 中导入您使用的字体
    <link
    rel="preload"
    href="/assets/my-font.woff2"
    as="font"
    type="font/woff2"
    />
  • 你的字体声明应该在 SSR HTML 页面上,所以使用 <style jsx global />将其包含在您的页面中。它可以是外部文件或直接在 style 中元素。
  • 关于reactjs - 使用 next.js 和样式组件重新加载时无样式文本 (FOUT) 的 Flash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60841540/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com