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>
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>
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!