You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React-Vite环境中使用本地字体并设置为默认字体?

在React-Vite环境中使用本地字体并设为默认字体的实现步骤

1. 整理字体文件与目录结构

把本地字体文件(比如示例里的Pretendard系列woff格式文件)放到项目的src/assets/fonts目录下,同时在该目录创建font.css文件用来配置字体规则。目录结构如下:

src/
├── assets/
│   ├── fonts/
│   │   ├── Pretendard-Regular.woff
│   │   ├── Pretendard-Medium.woff
│   │   ├── Pretendard-SemiBold.woff
│   │   ├── Pretendard-Bold.woff
│   │   └── font.css
├── App.jsx
└── main.jsx

2. 编写字体配置CSS

在font.css里通过@font-face定义不同权重的字体,再把全局元素的默认字体设置为该字体:

@font-face {
  font-family: "Pretendard";
  font-style: normal;
  font-weight: 400;
  src: url("@/assets/fonts/Pretendard-Regular.woff") format("woff");
}
@font-face {
  font-family: "Pretendard";
  font-style: normal;
  font-weight: 500;
  src: url("@/assets/fonts/Pretendard-Medium.woff") format("woff");
}
@font-face {
  font-family: "Pretendard";
  font-style: normal;
  font-weight: 600;
  src: url("@/assets/fonts/Pretendard-SemiBold.woff") format("woff");
}
@font-face {
  font-family: "Pretendard";
  font-style: normal;
  font-weight: 700;
  src: url("@/assets/fonts/Pretendard-Bold.woff") format("woff");
}

* {
  font-family: "Pretendard", sans-serif;
}

提示:路径里的@是Vite默认配置的别名,指向项目根目录下的src文件夹,保证能正确找到字体文件。

3. 在入口文件引入字体样式

打开项目入口文件main.jsx,引入写好的font.css,让字体规则全局生效:

import ReactDOM from "react-dom/client";
import App from "@/App.jsx";
import "@/assets/fonts/font.css";

ReactDOM.createRoot(document.getElementById("root")).render(<App />);

做完这三步,项目里所有元素都会默认使用Pretendard字体,不同权重的文本也会对应加载对应的字体文件。

内容的提问来源于stack exchange,提问作者ctr_nike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:25:14