Home >Web Front-end >CSS Tutorial >How to Use Fonts in Create-React-App Without Ejecting?

How to Use Fonts in Create-React-App Without Ejecting?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 21:47:03817browse

How to Use Fonts in Create-React-App Without Ejecting?

How to Incorporate Fonts into Create-React-App Projects Without Ejection

In order to utilize fonts in create-react-app projects without the need for ejection, there are two primary options available:

Method 1: Utilizing Imports

This approach involves importing CSS files into your JavaScript code. By default, src/index.js refers to src/index.css. Incorporate your fonts into this CSS file using relative paths starting with ./:

<code class="css">@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(./fonts/MyFont.woff) format('woff');
}</code>

Method 2: Employing the Public Folder

If you prefer not to employ the build pipeline, you can opt for the public folder approach. Place your fonts in the public/fonts directory:

public/fonts/MyFont.woff

Create a CSS file in the public folder, such as public/index.css, and manually link it in public/index.html:

<code class="html"><link rel="stylesheet" href="%PUBLIC_URL%/index.css"></code>

Inside public/index.css:

<code class="css">@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(fonts/MyFont.woff) format('woff');
}</code>

Recommendation

The initial method, leveraging imports, is highly recommended as it grants access to features like ensuring fonts pass through the build pipeline, acquiring hashes during compilation for efficient browser caching, and receiving compilation alerts if files are absent.

The above is the detailed content of How to Use Fonts in Create-React-App Without Ejecting?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn