如何在使用 tailwind css 时在本地将 google 字体添加到 Next.Js 项目

Kha*_*yar 0 javascript typescript reactjs next.js tailwind-css

对于我想要创建的网站,我想使用谷歌的“Work Sans”字体。我下载了“WorkSans-Black.ttf”文件,在“public”文件夹中创建了一个子文件夹“fonts”,并将文件放入其中。下面我为大家截图了文件夹结构。有人可以帮我吗,下一步是什么?

在此输入图像描述

ptt*_*tts 6

1.下载字体

下载字体并将其放在public/font目录中。我建议使用此工具下载 Google 字体:https://google-webfonts-helper.herokuapp.com/fonts/work-sans ?subsets=latin

2. 使用您的字体扩展 Tailwind 的字体堆栈

// tailwind.config.js

const defaultTheme = require('tailwindcss/defaultTheme')

module.exports = {
  theme: {
    extend: {
      fontFamily: {
        sans: ['Work Sans', ...defaultTheme.fontFamily.sans],
      },
    },
  },
  // ...
}
Run Code Online (Sandbox Code Playgroud)
// tailwind.css

@tailwind base;
@tailwind components;

// Repeat this for all the weights you downladed
@font-face {
  font-family: 'Work Sans';
  font-style: normal;
  font-weight: 400;
  src: local(''),
       url('public/fonts/work-sans-v9-latin-regular.woff2') format('woff2'),
       url('public/fonts/work-sans-v9-latin-regular.woff') format('woff');

@font-face {
  font-family: 'Work Sans';
  font-style: normal;
  font-weight: 100;
  src: local(''),
       url('public/fonts/work-sans-v9-latin-100.woff2') format('woff2'),
       url('public/fonts/work-sans-v9-latin-100.woff') format('woff');

@tailwind utilities;
Run Code Online (Sandbox Code Playgroud)

3.(可选)预加载字体以提高性能

// tailwind.config.js

const defaultTheme = require('tailwindcss/defaultTheme')

module.exports = {
  theme: {
    extend: {
      fontFamily: {
        sans: ['Work Sans', ...defaultTheme.fontFamily.sans],
      },
    },
  },
  // ...
}
Run Code Online (Sandbox Code Playgroud)