在create-react-app构建中完全包含Google网络字体(不弹出)

cod*_*kel 3 reactjs create-react-app google-fonts

我需要使用create-react-app在React webapp的构建中包括Google网络字体。这是因为该应用程序将在没有Internet访问的wifi上提供。最直接的解决方案似乎是google-fonts-webpack-plugin,但是它需要自定义的webpack配置。

是否有任何“简单”解决方案可以自动下载并包含所有网络字体资源,而无需从create-react-app中弹出?

sud*_*ang 7

有多种方法可以做到这一点。

1.导入字体

例如,要使用Roboto,请执行

yarn add typeface-roboto
Run Code Online (Sandbox Code Playgroud)

要么

npm install typeface-roboto --save
Run Code Online (Sandbox Code Playgroud)

在index.js中:

import "typeface-roboto";
Run Code Online (Sandbox Code Playgroud)

npm软件包包含许多开源字体和大多数Google字体。您可以在此处查看所有字体。所有软件包均来自该项目

2.手动下载字体并将其添加到样式表

您可以从fonts.google.com下载字体

fonts.google.com页面

现在,您可以将字体放入src/fonts/Lato.woff,然后在中使用它index.css

@font-face {
    font-family: 'Lato';
    src: local('Lato'), url(./fonts/Lato.woff) format('woff');
}
Run Code Online (Sandbox Code Playgroud)

对于ttf字体,您应该给truetype而不是ttf作为格式的参数

您可以将其导入到您的文件中index.js以使其可用

import './index.css';
Run Code Online (Sandbox Code Playgroud)

你可以做这些App.cssApp.js也是如此。这是您的偏爱。