在 nextjs 中使用谷歌字体与 sass、css 和语义 ui 反应

Sha*_*hua 10 css sass reactjs next.js

我有一个具有以下配置的 next.config.js 文件:

const withSass = require('@zeit/next-sass');
const withCss = require('@zeit/next-css');

module.exports = withSass(withCss({
  webpack (config) {
    config.module.rules.push({
      test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 100000,
          publicPath: './',
          outputPath: 'static/',
          name: '[name].[ext]'
        }
      }
    })

    return config
  }
}));
Run Code Online (Sandbox Code Playgroud)

这很棒,因为它运行我的语义 ui css 文件。

现在我有一个问题。我似乎无法成功导入任何谷歌字​​体网址。我尝试将 ttf 文件下载到我的文件路径中,并尝试使用 @import scss 函数引用它。但是我得到一个 GET http://localhost:3000/fonts/Cabin/Cabin- Regular.ttf net::ERR_ABORTED 404 (Not Found) 错误

这是我试图用谷歌字体做的事情:

@font-face {
  font-family: 'Cabin';
  src: url('/fonts/Cabin/Cabin-Regular.ttf')  format('truetype');
}

$font-size: 100px;
.example {
  font-size: $font-size;
  font-family: 'Cabin', sans-serif;
}
Run Code Online (Sandbox Code Playgroud)

我还下载了相关的 npm 依赖项:

"@zeit/next-css": "^1.0.1",
"@zeit/next-sass": "^1.0.1",
"file-loader": "^2.0.0",
"next": "^7.0.2",
"node-sass": "^4.9.4",
"react": "^16.6.0",
"react-dom": "^16.6.0",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^0.83.0",
"url-loader": "^1.1.2"
Run Code Online (Sandbox Code Playgroud)

Jgh*_*n14 11

我知道在Next.js 9.3 中,您可以从 Google Fonts复制@import语句:

@import url('https://fonts.googleapis.com/css2?family=Jost&display=swap');
Run Code Online (Sandbox Code Playgroud)

并将其放在某个 css 文件中,让我们这样说styles/fonts.css:

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

.jost {
  font-family: 'Jost', sans-serif;
}
Run Code Online (Sandbox Code Playgroud)

然后将其导入到全局_app.js文件中,如下所示:

import `../styles/fonts.css`
Run Code Online (Sandbox Code Playgroud)

现在,您可以全局访问每个 next.js 页面中包含 Google 字体的类


iur*_*rii 8

我认为另一种解决方案是直接从 Google 使用字体。只需自定义_app.js文件并<link rel="stylesheet" />在<Head />

示例_app.js

import React from 'react';
import App, { Container } from 'next/app';
import Head from 'next/head';

export default class MyApp extends App {
  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps };
  }

  render() {
    const { Component, pageProps } = this.props;

    return (
      <Container>
        <Head>
          <link
            href="https://fonts.googleapis.com/css?family=Cabin"
            rel="stylesheet"
            key="google-font-cabin"
          />
        </Head>

        <Component {...pageProps} />

        <style global jsx>{`
          body {
            font-family: 'Cabin', sans-serif;
          }
        `}</style>
      </Container>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*hua 0

我必须将文件放入静态文件夹才能工作,必须是在 nextjs 中渲染图像和字体的特定设置