🖋でフォントを追加する.js (ローカルフォントとスタイルコンポーネント)



ステップ1 -次を作成します.アプリケーション
私はすべての開発フォルダーをデスクトップにするので、私は
cd Desktop
npx create-next-app
//Running this script on the folder you want to store the project folder
* Will ask you whats your project name? projectName
/*
Enter the project name and it will create a folder with that name along 
with all the neccessary files
*/

ステップ2 -カスタムフォントを追加する(ローカル)
📁 ページ
📁 公共
⠀⠀⠀📁 フォント
⠀⠀⠀⠀⠀⠀FontNameスタイル.ワンド

ステップ3 -これらのフォントを押下します.js
ドキュメントを作成します.JSファイルを既にしていない場合は、次のコードを追加すると、ヘッド内のフォントをプリロードします.
スタイル付きコンポーネントを使用していない場合は、静的になるまでのすべてを削除すべきです.

KHIドキュメントjs
import Document, {Html, Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
//--------------For styled-components only------------//
  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()
    }
  }
//---------------------------------------------------//
  render() {
    return (
        <Html lang="en">
            <Head>
                <link
                  rel="preload"
                  href="/fonts/ProximaNova-Bold.woff"
                  as="font"
                  type="font/woff"
                  crossOrigin=""
                />
                <link
                  rel="preload"
                  href="/fonts/ProximaNova-Regular.woff"
                  as="font"
                  type="font/woff"
                  crossOrigin=""
                />
            </Head>
            <body>
                <Main />
                <NextScript />
            </body>
        </Html>
    );
}
}
  • ここで重要なことは、頭の中のタグです.

  • ps : HTML =//HTML
    このHTMLは全てのページに共通のものです.
    タイトルとメタを使用するためには、特定のページの中で
  • タグ.
  • また、レンダリング以外のすべてのコードがどのような意味を持つのかわからない場合は、スタイルのコンポーネントをサーバー側で動作させるためだけに、スタイルのコンポーネントを使用してスタイリングを選択します.次のスタイルのコンポーネントを理解するためにチェックアウト.詳細はJS.

  • エキストラ
    短い答え:はい、両方を使用することができます.彼らは異なる目的を提供し、同じアプリケーションで使用することができます.
    NextJSウェブサイトによって

    Next.js uses the App component to initialize pages.To override, create the ./pages/_app.js file and override the App class


    and

    Pages in Next.js skip the definition of the surrounding document's markup. For example, you never include , 

    , etc. To override that default behavior, you must create a file at ./pages/_document.js, where you can extend the Document class.

    備考_document.js そして、クライアント側ではなくサーバー側でのみ表示されます.したがって、onClick 彼女は仕事に行かない.

    ステップ4 -グローバルに宣言する
    (再度、スタイルコンポーネントを使用します.

    を作成するアプリ.あなたのページフォルダ内のJSファイルは、すでにない場合は、追加します.下記
    import { createGlobalStyle } from "styled-components";
    
    const GlobalStyle = createGlobalStyle`
        @font-face {
        font-family: 'ProximaNova-Regular';
        src: url('/fonts/ProximaNova-Regular.woff') format('woff');
        font-style: normal;
        font-weight: 400;
        font-display: swap;
      }
      @font-face {
        font-family: 'ProximaNova-Bold';
        src: url('/fonts/ProximaNova-Bold.woff') format('woff');
        font-style: bold;
        font-weight: 700;
        font-display: swap;
      }
    `;
    
    function MyApp({ Component, pageProps }) {
      return (
        <>
          <GlobalStyle />
          <Component {...pageProps} />
        </>
      );
    }
    
    export default MyApp
    
    ここで起こっているwhats?
    私の世界的なスタイルで私は@フォントフェースを宣言しています、そして、各々の顔の源は我々がちょうど作成したフォント・フォルダの中でフォント顔のURLを指し示しています.
  • @フォントの顔を使用して注意してください、各フォントファミリーの名前が異なっていると実際のフォントファイルに従って.
  • フォントの表示をスワップします.
  • 今ここでは、フォントの表示を実際に知って興味を持っている場合Check out this article on CSS-tricks また、これはFoutとFitを理解するのに役立つことができますover here .

    それはthats!テストします.
    次に、インデックス内に次のコードを追加します.js

    インデックス.js
    import Head from 'next/head'
    // import styles from '../styles/Home.module.css'
    import styled from  'styled-components';
    const Test1 = styled.p`
      font-size: 40px;
      font-family: 'ProximaNova-Regular';
      color: #00688B;
    `;
    const Test2 = styled.p`
      font-size: 40px;
      font-family: 'ProximaNova-Bold';
      color: #00688B;
    `;
    
    export default function Home() {
      return (
        <div>
          <Head>
            <title>Create Next App</title>
            <link rel="icon" href="/favicon.ico" />
          </Head>
          <main>
            <Test1>Test1</Test1>
            <Test2>Test2</Test2>
          </main>
        </div>
      )
    
    これを追加すると、フォルダ内の端末に移動して実行します.
    $ yarn dev
    // $ just mean run it inside your bash terminal you just need to copy "yarn dev"
    
    一旦これが行われるならばhttps://localhost.3000 そして、あなたの次を見てください.実行中のJSアプリ.


    参考:
    Safari開発ツールとGoogle Chrome開発ツールをチェックしてください.
    あなたがフォントファイルを見ることができるならば、あなたがそこで、そして、彼らの内部でフォントフォルダを見るならば.それはおそらく、あなたのfontfilesが正常に出されたことを意味します.
    サファリ

    グーグルクローム


    重要なリンク

  • 次のオープンソースリポジトリを見てください.実際のサイト.https://github.com/vercel/next-site
    具体的には、/style/fontsの中でフォントを宣言した方法を見てください.JSとは、アプリ内で呼び出している.js
  • あなたが密接に観察するならば、あなたのプロジェクトで起こっているフォントのフラッシュがあるかもしれませんhttps://leerob.io/blog/things-ive-learned-building-nextjs-apps
  • 私も発見this repository これは、同じライブラリ(次の+スタイルのコンポーネント)を使用して任意の更新プログラムを見てみることができます.

  • 私の作った間違い
    他の何かを試みる前に、次のフォントと呼ばれるライブラリを使っていました.設定.jsファイル.しかし、話すときにライブラリを廃止すると、直接任意のライブラリなしでフォントを使用することができます.
    このファイルは2つのライブラリを使用します:
  • 次のフォント
  • @次のCSS
  • const withCss = require("@zeit/next-css");
    const withFonts = require("next-fonts");
    
    module.exports = withFonts(
      withCss({
        webpack: (config, { isServer }) => {
          if (isServer) {
            const antStyles = /antd\/.*?\/style\/css.*?/;
            const origExternals = [...config.externals];
            config.externals = [
              (context, request, callback) => {
                if (request.match(antStyles)) return callback();
                if (typeof origExternals[0] === "function") {
                  origExternals[0](context, request, callback);
                } else {
                  callback();
                }
              },
              ...(typeof origExternals[0] === "function" ? [] : origExternals)
            ];
    
            config.module.rules.unshift({
              test: antStyles,
              use: "null-loader"
            });
          }
          return config;
        }
      })
    );
    
    または@ zeit/next cssをインストールするだけです
    const withCSS = require('@zeit/next-css')
    
    module.exports = withCSS({
      cssLoaderOptions: {
        url: false
      }
    })
    
    このファイルのポイントはCSSモジュールを停止して競合を防止します.しかし、私は個人的に自分のサイトのためにそれを使用していない.

    これを可能にするリンク
    https://stackoverflow.com/questions/60841540/flash-of-unstyled-text-fout-on-reload-using-next-js-and-styled-components
    https://codeconqueror.com/blog/using-google-fonts-with-next-js
    https://leerob.io/blog/things-ive-learned-building-nextjs-apps
    https://github.com/styled-components/styled-components/issues/3224
    How to avoid layout shifts caused by web fonts