在Create React App构建的Storybook中添加@font-face失效问题排查求助
Let’s walk through the most likely issues and fixes for your custom font not loading correctly:
1. Missing path Module Import in Webpack Config
Your webpack.config.js uses path.resolve but doesn’t import the Node.js path module first. This will throw an error that prevents the font file processing rule from being applied at all.
Fix your webpack.config.js:
const path = require('path'); // Add this line at the top module.exports = async ({ config }) => { config.module.rules.push({ test: /\.(woff|woff2|eot|ttf|svg)$/, use: [ { loader: 'file-loader', options: { // Replace deprecated `query` with `options` for modern file-loader name: '[name].[ext]', outputPath: 'fonts/', // Optional: Organize fonts into a dedicated directory publicPath: './fonts/' // Ensures the correct reference path for the font }, }, ], include: path.resolve(__dirname, '../'), }); return config; };
2. Incorrect Font Path in preview-head.html
The path in your @font-face rule points to your source file location (shared/fonts/...), but after webpack processes the files, the font is copied to Storybook’s build output directory—not your source directory.
Update your preview-head.html:
If you added outputPath: 'fonts/' to the webpack config:
<style> @font-face { font-family: 'WalsheimPro'; font-style: normal; font-weight: 400; src: url('fonts/GTWalsheimProMedium.ttf') format('truetype'); } </style>
If you didn’t set outputPath, the font will live in the root output directory:
<style> @font-face { font-family: 'WalsheimPro'; font-style: normal; font-weight: 400; src: url('GTWalsheimProMedium.ttf') format('truetype'); } </style>
3. Verify Font Usage in CSS Modules
Double-check that you’re actually applying the font in your CSS Modules and referencing the class correctly in your component:
In your component’s CSS Module (e.g., MyComponent.module.css):
.customText { font-family: 'WalsheimPro', sans-serif; }
In your React component:
import styles from './MyComponent.module.css'; const MyComponent = () => { return <div className={styles.customText}>Text using custom font</div>; };
4. Clear Caches
Cached resources can block the new font from loading:
- Force-refresh your browser (Ctrl+Shift+R on Windows/Linux, Cmd+Shift+R on Mac)
- Delete Storybook’s cache: Remove the
node_modules/.cache/storybookdirectory - Restart your Storybook development server
5. Validate Network Requests for the Font
Open your browser’s DevTools > Network tab, then refresh the page. Look for your font file (GTWalsheimProMedium.ttf):
- If you see a 404 error: The path in
preview-head.htmlis still wrong. Adjust it to match where webpack outputs the font. - If the request succeeds but the font doesn’t render: Confirm the font file is valid, and that the
font-familyname in your CSS exactly matches the one defined in@font-face.
内容的提问来源于stack exchange,提问作者Sanne Wintrén

