ReactJS应用自定义字体加载失败,控制台报OTS解析错误求解决
Hey there, let's troubleshoot why your Poppins font isn't loading in your React app—especially since it works fine in a plain HTML/CSS setup. The OTS parsing error: invalid version tag usually points to a path mismatch or incorrect webpack configuration handling your font files. Here's how to fix it:
1. Verify Your Font File Placement
In React apps (whether using Create React App or a custom webpack setup), static assets like fonts need to be in a location where the build tool can resolve them properly:
- If you’re using the
publicfolder: Place yourfontsdirectory directly insidepublic(so the full path ispublic/fonts/poppin/Poppins-Light.otf). This lets your absolute URL/fonts/poppin/Poppins-Light.otfwork as expected. - If bundling fonts via webpack: Keep the
fontsfolder in your source directory (e.g.,src/fonts) and ensure webpack’s loader can locate it via theincluderule.
2. Fix Your Webpack Configuration
Your current webpack setup has a couple of issues that might be breaking font loading:
- Outdated syntax: Webpack 2+ uses
rulesinstead ofloaders—mixing both can cause conflicts. - Mismatched path settings: The current
outputPathandpublicPathare sending fonts to thecss/folder and adjusting references in a way that doesn’t align with where files end up.
Update your webpack config’s module.rules section to this:
module.exports = { module: { rules: [ // Handle font files { test: /\.(woff|woff2|ttf|otf)$/, loader: 'file-loader', include: [/fonts/], // Ensure this matches your fonts folder's path options: { name: '[name].[ext]', // Keep original filenames for easier debugging outputPath: 'fonts/', // Bundle fonts into a dedicated fonts folder publicPath: './fonts/' // Make sure CSS references the correct path to fonts } }, // Handle CSS files { test: /\.css$/, use: ['style-loader', 'css-loader'] // Use 'use' for multiple loaders (webpack 2+ standard) }, // Handle Jade files { test: /\.jade$/, loader: 'jade-loader?self' } ] }, node: { fs: "empty" } }
3. Adjust Your CSS Font Reference
If you’re bundling fonts via webpack (not using the public folder), update your @font-face rule to use a relative path. This lets webpack resolve the font file and process it with the file-loader:
@font-face { font-family: Poppins; src: url('./fonts/poppin/Poppins-Light.otf'); // Relative to your index.css file } body{ margin: 0; padding: 0; font-family: Poppins; font-size: 16px; line-height: 1.2em; }
4. Double-Check the Font File
Even though it works in plain HTML, cached files or minor corruption can cause issues in React’s dev server. Try:
- Clearing your browser cache and restarting the React dev server
- Re-downloading the Poppins font file to ensure it’s not corrupted
Once you make these changes, rebuild your app and the font should load without the parsing error!
内容的提问来源于stack exchange,提问作者Elcid_91




