如何在Vite项目中导入Google Font?(React+TypeScript+Sass环境)
在Vite+React+TypeScript+Sass项目中导入Google Font的几种方案
方案1:直接在index.html中引入
这是最直接的方式,无需额外配置。打开项目根目录的index.html,在<head>标签内添加Google Font的链接标签,以导入Roboto字体为例:
<head> <!-- 保留原有内容 --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet"> </head>
之后即可在Sass或TSX的样式中直接使用:
body { font-family: 'Roboto', sans-serif; }
方案2:在Sass文件中通过@import导入
若习惯在样式文件内统一管理资源,可在全局Sass文件(如src/index.scss)中用@import引入:
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap'); body { font-family: 'Roboto', sans-serif; }
Vite会自动处理该URL引入,无需额外配置。
方案3:本地导入Google Font(脱离网络依赖)
若想避免外部网络请求,可将字体文件下载到本地使用:
- 从Google Fonts官网下载目标字体的压缩包,解压后放入项目的
src/assets/fonts目录 - 在全局Sass文件中通过
@font-face声明字体:
@font-face { font-family: 'Roboto'; src: url('../assets/fonts/Roboto-Regular.ttf') format('truetype'); font-weight: 400; font-style: normal; } @font-face { font-family: 'Roboto'; src: url('../assets/fonts/Roboto-Medium.ttf') format('truetype'); font-weight: 500; font-style: normal; } body { font-family: 'Roboto', sans-serif; }
这种方式适合离线开发或对加载速度要求较高的场景。
注意事项
- 确保使用的字体权重(weight)、样式(style)与引入的配置一致,避免触发 fallback 字体
- 使用TypeScript时无需额外类型配置,直接在样式中调用字体名称即可
内容的提问来源于stack exchange,提问作者koalatree
相关产品推荐
相关产品推荐

