【问题标题】:using google fonts in nextjs with sass, css and semantic ui react在带有 sass、css 和语义 ui 的 nextjs 中使用谷歌字体
【发布时间】:2019-04-06 06:27:18
【问题描述】:

我有一个具有以下配置的 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
  }
}));

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

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

这是我尝试用 google 字体做的事情:

@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;
}

我也下载了相关的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"

【问题讨论】:

    标签: css reactjs sass next.js


    【解决方案1】:

    如果您使用的是功能性自定义应用程序,那么您可以将 google 字体或任何 cdn 链接字体添加到整个应用程序的头部,如下所示:

    import Head from 'next/head';
    
    // Custom app as a functional component
    function MyApp({ Component, pageProps }) {
      return (
        <>
          <Head>
            <link
              href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@300;400;600;700&display=swap" rel="stylesheet"/>
          </Head>
          <Component {...pageProps}/>
        </>
      )
    }
    
    MyApp.getInitialProps = async ({ Component, ctx }) => {
      let pageProps = {};
      if (Component.getInitialProps) {
        pageProps = await Component.getInitialProps(ctx);
      }
    
      return { pageProps };
    };
    
    // Export app
    export default MyApp
    

    现在您可以使用 css 将字体系列应用于 body 元素,以使字体在整个 webiste 中应用,如下所示。

    body {
      font-family: 'Source Sans Pro', sans-serif;
    }
    

    【讨论】:

      【解决方案2】:

      根据最新的docs,您现在可以通过更新_app.js 文件并导入您的css 样式来添加全局css。请按照以下步骤操作

      1. 按照docs在pages目录下创建自定义_app.js文件。
      2. 将您的 styles.css 文件添加到 pages 目录。
      3. 包括以下样式

      // _app.js
      
      // Import styles
      import './styles.css'
      
      // Function to create custom app
      function MyApp({ Component, pageProps }) {
        return <Component {...pageProps} />
      }
      
      // Export app
      export default MyApp

      然后完成。这些样式styles.css 将应用于您应用程序中的所有页面和组件。由于样式表的全局性,为了避免冲突,您只能在 _app.js 中导入它们。

      【讨论】:

        【解决方案3】:

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

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

        并将其放在某个 css 文件中,比如 styles/fonts.css

        @import url('https://fonts.googleapis.com/css2?family=Jost&display=swap');
        
        .jost {
          font-family: 'Jost', sans-serif;
        }
        

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

        import `../styles/fonts.css`
        

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

        【讨论】:

        • 我认为这是最佳做法。
        【解决方案4】:

        这就是我当前非阻塞加载外部字体的方式。在 _document.js 头中:

        <script dangerouslySetInnerHTML={{__html: '</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" media="print" onload="this.media=\'all\'" /><script>' }} />
        
        • dangerouslySetInnerHTML 和一些脚本黑客可以解决 onload 否则将从 _document.js until this is resolved 中删除

        source

        【讨论】:

          【解决方案5】:
           class NextApp extends App {
            render() {
              const { Component } = this.props
              return (
                    <React.Fragment>
                      <Component {...pageProps} />
          
                      <style jsx="true" global>{`
          
                        @import url('https://fonts.googleapis.com/css?family=Roboto');
          
                        body {
                          margin: 0;
                          font-family: 'Roboto', sans-serif;
                        }
          
                      `}</style>
          
                    </React.Fragment>
                  </Provider>
                </Container>
              )
            }
          }
          

          在 styled-jsx 中包含来自 Google Fonts 的字体 url 对我有用。

          【讨论】:

            【解决方案6】:

            我认为另一种解决方案是直接使用 Google 提供的字体。只需自定义_app.js file 并在&lt;Head /&gt; 中添加&lt;link rel="stylesheet" /&gt;

            示例 _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>
                );
              }
            }
            

            【讨论】:

            • 您认为最佳做法是什么?将字体存放在本地文件夹中还是您刚刚建议的?
            • 当我使用来自 Google via API 的字体而不是在本地下载字体时,我会采用这种方法。我看到的一些好处: 1. 如果我需要从谷歌添加更多字体,我不需要下载任何东西,只需在 URL 中添加字体名称即可 2. 无需调整 next.js webpack 配置来加载字体
            • 效果很好。不过我会把它放到 _document.js 中。
            • 我会考虑本地复制最佳实践 - 连同 css 字体显示设置,您可以避免不必要的网络请求
            【解决方案7】:

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

            【讨论】:

              猜你喜欢
              • 2022-01-19
              • 2014-05-20
              • 1970-01-01
              • 2021-04-05
              • 1970-01-01
              • 1970-01-01
              • 2015-03-26
              • 2021-06-17
              • 1970-01-01
              相关资源
              最近更新 更多