使用 NextJS 的自托管字体 [英] Self-hosted fonts using NextJS

查看:172
本文介绍了使用 NextJS 的自托管字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用我的 NextJS 应用程序自托管 webfonts,但遇到了问题.这是 URL 浏览器尝试访问这些字体:

localhost:3000/_next/static/css/fonts/Avenir.woff2

实际路径为:

_project_dir/static/fonts/Avenir.woff2

我尝试在 _app.js 中包含链接,它确实下载了字体,但文本仍然没有样式.

这是我的 _app.js:

<预><代码>使成为() {const { Component, pageProps } = this.props;返回 (<容器><link href="https://fonts.googleapis.com/css?family=Poppins:500,500i,600&display=swap";rel=样式表"/><link rel=预加载"as=字体"href="/static/fonts/Avenir.woff2";type="font/woff2";跨域/><link rel=预加载"as=字体"href="/static/fonts/AvenirHeavy.woff2";type="font/woff2";跨域/><头><title>项目</title></头><提供者商店={商店}><PersistGate loading={null} persistor={persistor}><组件 pageContext={this.pageContext} {...pageProps}/></PersistGate></提供者></容器>);}}

我的main.css

@font-face {字体系列:'Avenir';字体粗细:400;字体样式:正常;字体显示:交换;src: url('fonts/Avenir.eot');src: url('fonts/Avenir.eot?#iefix') 格式('embedded-opentype'), url('fonts/Avenir.woff2') 格式('woff2'),url('fonts/Avenir.woff') 格式('woff'), url('fonts/Avenir.ttf') 格式('truetype');}@字体脸{字体系列:'Avenir';字体粗细:500;src: url('fonts/Avenir.eot');src: url('fonts/Avenir.eot?#iefix') 格式('embedded-opentype'), url('fonts/Avenir.woff2') 格式('woff2'),url('fonts/Avenir.woff') 格式('woff'), url('fonts/Avenir.ttf') 格式('truetype');}@字体脸{字体系列:'Avenir';字体粗细:900;src: url('fonts/AvenirHeavy.eot');src: url('fonts/AvenirHeavy.eot?#iefix') 格式('embedded-opentype'), url('fonts/AvenirHeavy.woff2') 格式('woff2'),url('fonts/AvenirHeavy.woff') 格式('woff'), url('fonts/AvenirHeavy.ttf') 格式('truetype');}

还有我的next.config.js:

 webpack(config, options) {config.module.rules.push({测试:/\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,用: {loader: 'url-loader',选项: {限制:100000,},},});返回配置;},

解决方案

在 Next 的较新版本中,我相信您可以导入 WOFF2 文件并在您的 CSS 类似于这个例子 为盖茨比.但是,如果您不导入字体文件,而是按照您的解释将它们放在 /static/fonts 目录中,则可以避免使用 WebPack 加载程序或像 next-fonts 通过硬编码静态目录中的字体路径 按照亚历克斯的建议:

import React, { Fragment } from "react";const WebFonts = () =>(<片段><样式全局jsx>{`@字体脸{字体系列:Source Sans Pro";字体样式:正常;字体拉伸:正常;字体粗细:400;字体显示:回退;src: local(SourceSansPro Regular"), local(SourceSansPro-Regular"),url(/static/fonts/SourceSansPro-Regular.woff2) 格式(woff2");Unicode 范围:U+0100-024f、U+1-1eff、U+20a0-20ab、U+20ad-20cf、U+2c60-2c7f、U+A720-A7FF;}@字体脸{字体系列:Source Sans Pro";字体样式:正常;字体粗细:600;字体显示:回退;src:本地(SourceSansPro SemiBold"),本地(SourceSansPro-SemiBold"),url(/static/fonts/SourceSansPro-SemiBold.woff2) 格式(woff2");Unicode 范围:U+0100-024f、U+1-1eff、U+20a0-20ab、U+20ad-20cf、U+2c60-2c7f、U+A720-A7FF;}@字体脸{字体系列:Source Sans Pro";字体样式:正常;字体粗细:700;字体显示:回退;src:本地(SourceSansPro SemiBold"),本地(SourceSansPro-SemiBold"),url(/static/fonts/SourceSansPro-Bold.woff2) 格式(woff2");Unicode 范围:U+0100-024f、U+1-1eff、U+20a0-20ab、U+20ad-20cf、U+2c60-2c7f、U+A720-A7FF;}`}</style></片段>);导出默认的 WebFonts;

然后将该组件导入 NextJS 中的 _document 覆盖.这将使用添加到 NextJS 静态目录中的字体.请务必使用 woff2<提供的 woff2_compress 方法压缩从 Google 字体下载的任何 TTF 字体./a> 在为它们提供更好的页面速度之前.如果您没有在 DevTools 的网络瀑布中看到您的本地字体下载,请确保通过删除这些字体的任何本地版本或 local 字体声明进行测试.

I'm trying to self-host webfonts using my NextJS app and having trouble. This is the URL browser tries to access these fonts:

localhost:3000/_next/static/css/fonts/Avenir.woff2

The actual path is:

_project_dir/static/fonts/Avenir.woff2

I tried including the link in the the _app.js, it does download the fonts, but the text remains unstyled.

<link rel="preload" as="font" href="/static/fonts/Avenir.woff2" type="font/woff2" crossorigin />

Here's my _app.js:


  render() {
    const { Component, pageProps } = this.props;
    return (
      <Container>
        <link href="https://fonts.googleapis.com/css?family=Poppins:500,500i,600&display=swap" rel="stylesheet" />
        <link rel="preload" as="font" href="/static/fonts/Avenir.woff2" type="font/woff2" crossorigin />
        <link rel="preload" as="font" href="/static/fonts/AvenirHeavy.woff2" type="font/woff2" crossorigin />
        <Head>
          <title>Project</title>
        </Head>
        <Provider store={store}>
          <PersistGate loading={null} persistor={persistor}>
            <Component pageContext={this.pageContext} {...pageProps} />
          </PersistGate>
        </Provider>
      </Container>
    );
  }
}

My main.css

@font-face {
  font-family: 'Avenir';
  font-weight: 400;
  font-style: normal;
  font-display: swap;
  src: url('fonts/Avenir.eot');
  src: url('fonts/Avenir.eot?#iefix') format('embedded-opentype'), url('fonts/Avenir.woff2') format('woff2'),
    url('fonts/Avenir.woff') format('woff'), url('fonts/Avenir.ttf') format('truetype');
}

@font-face {
  font-family: 'Avenir';
  font-weight: 500;
  src: url('fonts/Avenir.eot');
  src: url('fonts/Avenir.eot?#iefix') format('embedded-opentype'), url('fonts/Avenir.woff2') format('woff2'),
    url('fonts/Avenir.woff') format('woff'), url('fonts/Avenir.ttf') format('truetype');
}

@font-face {
  font-family: 'Avenir';
  font-weight: 900;
  src: url('fonts/AvenirHeavy.eot');
  src: url('fonts/AvenirHeavy.eot?#iefix') format('embedded-opentype'), url('fonts/AvenirHeavy.woff2') format('woff2'),
    url('fonts/AvenirHeavy.woff') format('woff'), url('fonts/AvenirHeavy.ttf') format('truetype');
}

And my next.config.js:

  webpack(config, options) {
    config.module.rules.push({
      test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 100000,
        },
      },
    });
    return config;
  },

In newer versions of next I believe you can import the WOFF2 file and use that in your CSS similar to this example for Gatsby. However, if you're not importing font files and instead placing them in the /static/fonts directory as you explain you can avoid using the WebPack loader or a plugin like next-fonts by hard-coding the font paths in your static directory as suggested by Alex:

import React, { Fragment } from "react";

const WebFonts = () => (
  <Fragment>
    <style global jsx>{`
      @font-face {
        font-family: "Source Sans Pro";
        font-style: normal;
        font-stretch: normal;
        font-weight: 400;
        font-display: fallback;
        src: local("SourceSansPro Regular"), local("SourceSansPro-Regular"),
          url(/static/fonts/SourceSansPro-Regular.woff2) format("woff2");
        unicode-range: U+0100-024f, U+1-1eff, U+20a0-20ab, U+20ad-20cf, U+2c60-2c7f,
          U+A720-A7FF;
      }
      @font-face {
        font-family: "Source Sans Pro";
        font-style: normal;
        font-weight: 600;
        font-display: fallback;
        src: local("SourceSansPro SemiBold"), local("SourceSansPro-SemiBold"),
          url(/static/fonts/SourceSansPro-SemiBold.woff2) format("woff2");
        unicode-range: U+0100-024f, U+1-1eff, U+20a0-20ab, U+20ad-20cf, U+2c60-2c7f,
          U+A720-A7FF;
      }
      @font-face {
        font-family: "Source Sans Pro";
        font-style: normal;
        font-weight: 700;
        font-display: fallback;
        src: local("SourceSansPro SemiBold"), local("SourceSansPro-SemiBold"),
          url(/static/fonts/SourceSansPro-Bold.woff2) format("woff2");
        unicode-range: U+0100-024f, U+1-1eff, U+20a0-20ab, U+20ad-20cf, U+2c60-2c7f,
          U+A720-A7FF;
      }
    `}</style>
  </Fragment>
);

export default WebFonts;

And then importing that Component into your _document override in NextJS. This will use fonts added to the NextJS static directory. Be sure to compress any TTF font downloads from Google Fonts using the woff2_compress method provided by woff2 before serving them for better page speed. And if you're not seeing your local font downloads appearing in the Network waterfall in DevTools make sure you test by removing any local versions of those fonts or local font face declarations.

这篇关于使用 NextJS 的自托管字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆