How do I manage fonts effectively in create-react-app without ejecting?

Linda Hamilton
Release: 2024-11-06 18:20:02
Original
418 people have browsed it

How do I manage fonts effectively in create-react-app without ejecting?

Managing Fonts in create-react-app

When using create-react-app without ejecting, the placement of fonts imported via @font-face can be confusing. Here are two options to consider:

Using Imports

This is the recommended approach as it integrates the fonts into the build pipeline, ensuring correct browser caching and compilation errors if files are missing. Import a CSS file from your JavaScript file, such as src/index.js importing src/index.css. Within the CSS file, define the @font-face rule with a relative path to the font file within the src/fonts directory, e.g.:

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

Using Public Folder

While this method is not recommended, it involves placing fonts in the public folder, e.g., public/fonts/MyFont.woff. In this case, create a CSS file in the public folder, such as public/index.css, and manually add a link to it in public/index.html. Within the CSS file, use the regular CSS notation with a relative path to the font file within the public/fonts directory, e.g.:

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

However, this method has drawbacks such as missing hashes and minification, leading to slower loading and potential caching issues.

Recommendation

The first method, "Using Imports," is preferred as it ensures proper handling of fonts within the build pipeline and avoids potential problems.

The above is the detailed content of How do I manage fonts effectively in create-react-app without ejecting?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!