You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Storybook中Google Font(Manrope)无法加载问题求助

在React Storybook中使用Manrope字体不生效的问题

我已参考官方文档、StackOverflow及GitHub相关方案,尝试在React Storybook中导入Manrope字体:

  • 已在.storybook目录下创建preview-head.html文件,代码如下:
<link rel="preload" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800" />
<!-- Or you can load custom head-tag JavaScript: -->
<script src="https://use.typekit.net/xxxyyy.js"></script>
<script>try{ Typekit.load(); } catch(e){ }</script>

但在styled-components中使用该字体时无法生效,代码示例:

export const Initials = styled.div`
  color: ${color.midnightBlue};
  font-family: Manrope;
  font-size: 24px;
  width: 100%;
  padding: 0px 33px;
  font-weight: ${typography.weight.extrabold}; //800
`;

我的preview.js文件内容如下:

/** @type { import('@storybook/react').Preview } */
const preview = {
decorators: [
  (Story) => (
    <>
      <Story />
    </>
  ),
],
 parameters: {
   actions: { argTypesRegex: '^on[A-Z].*' },
   controls: {
     matchers: {
       color: /(background|color)$/i,
       date: /Date$/,
     },
   },
 },
};

export default preview;

请问是否缺少相关配置?是否需要添加加载器?


解决方案

1. 修复preview-head.html的字体加载逻辑

你当前用preload仅会预加载资源,不会实际应用字体。需要修改rel属性并补充跨域配置,同时删除无关的Typekit脚本(你用的是Google Fonts的Manrope,和Typekit无关):

<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800" crossorigin />

2. 确保字体族配置准确

在styled-components中给字体添加 fallback 选项,同时确认字体名称拼写和权重值正确:

export const Initials = styled.div`
  color: ${color.midnightBlue};
  font-family: 'Manrope', sans-serif;
  font-size: 24px;
  width: 100%;
  padding: 0px 33px;
  font-weight: 800; // 直接写数值避免变量取值错误
`;

3. 全局注入字体样式(备选方案)

如果上述修改仍不生效,可以在preview.js中通过全局样式强制导入字体:

/** @type { import('@storybook/react').Preview } */
import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  @import url('https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap');
  * {
    font-family: 'Manrope', sans-serif;
  }
`;

const preview = {
decorators: [
  (Story) => (
    <>
      <GlobalStyle />
      <Story />
    </>
  ),
],
 parameters: {
   actions: { argTypesRegex: '^on[A-Z].*' },
   controls: {
     matchers: {
       color: /(background|color)$/i,
       date: /Date$/,
     },
   },
 },
};

export default preview;

4. 清除浏览器缓存

强制刷新页面(Ctrl+Shift+R)或清空浏览器缓存,避免旧资源缓存导致字体未加载。

内容的提问来源于stack exchange,提问作者coding1223322

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 17:22:22