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

How to Add Fonts to Create-React-App Projects Without Ejecting?

DDD
DDDOriginal
2024-11-05 15:50:02226browse

How to Add Fonts to Create-React-App Projects Without Ejecting?

Adding Fonts to Projects Based on create-react-app without Ejecting

Using the build pipeline is the recommended method for adding fonts to create-react-app projects. This ensures proper processing, hashes for browser caching, and compilation error detection.

  1. Using Imports:

    • Import a CSS file from JS, such as src/index.css from src/index.js.
    • Reference fonts in the CSS file using relative paths, like:

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

    • Place fonts in public/fonts/MyFont.woff.
    • Create a CSS file in the public folder, such as public/index.css.
    • Add a link to this CSS file in public/index.html:

      <code class="html"><link rel="stylesheet" href="%PUBLIC_URL%/index.css"></code>
    • Reference fonts in the CSS file using the relative path fonts/MyFont.woff.

Note that using the public folder method is not preferred as it doesn't ensure proper processing, hashing, or error detection. It's also more prone to caching issues.

Regardless of the method, you'll need to have the fonts in a supported format, such as WOFF, WOFF2, or TTF.

The above is the detailed content of How to Add Fonts to Create-React-App Projects 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