Nextjs 添加本地字体及google字体

google字体

创建_document.tsx

import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  static async getInitialProps(ctx:any) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html>
        <Head>
          <link
            href="https://fonts.googleapis.com/css2?family=Lobster"
            rel="stylesheet"
          />
          <link
            href="https://fonts.googleapis.com/css2?family=Roboto Condensed"
            rel="stylesheet"
          />

        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

本地字体(一)

image.png

_document.tsx

<Head>
  {/* <link
  href="https://fonts.googleapis.com/css2?family=Noto Sans Simplified Chinese"
  rel="stylesheet"
  /> */}
  <link rel="stylesheet" href="/fonts/font.css"></link>
</Head>

本地字体(二)

安装 next-fonts url-loader file-loader

  • next.config.js
const withFonts = require("next-fonts");

const nextConfig = withFonts({
  webpack(config, options) {
    // config.node = {
    //     fs: "empty",
    // };
    config.module.rules.push({
        test: /\.(png|woff|woff2|eot|ttf|svg)$/,
        use: [
            options.defaultLoaders.babel,
            {
                loader: "url-loader?limit=100000",
            },
            {
                loader: "file-loader",
            },
        ],
    });
    return config;
  },
  reactStrictMode: true,
  swcMinify: true,
  // distDir: 'build',
  exportPathMap: async function (
      defaultPathMap,
      { dev, dir, outDir, distDir, buildId }
  ) {
      return {
          '/': { page: '/' },
      };
  },
  images: {
      loader: 'akamai',
      path:'',
  }
});

module.exports = nextConfig
  • globals.css
@font-face {
  font-family: 'HYk2gj';
  src: url('/fonts/HYk2gj.ttf') format('truetype');
  font-style: normal;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容