故事书自定义字体未显示

时间:2019-10-04 09:31:43

标签: javascript reactjs storybook

我有一个Material UI主题,如下所示:

import { createMuiTheme } from '@material-ui/core/styles'

const primaryColor = '#009baa'

const theme = createMuiTheme({
  typography: {
    fontFamily: ['custom font here'].join(','),
    h1: { color: primaryColor },
    h2: { color: primaryColor, fontSize: '26px' },
  },
  palette: {
    primary: {
      main: primaryColor,
    },
  },
  overrides: {
    MuiButton: {
      root: {
        background: primaryColor,
        textTransform: 'none',
      },
    },
  },
})

export default theme

像这样在我的主应用程序中使用:

...
      <ThemeProvider theme={theme}>
        <Provider store={store}>
          <Calendar />
        </Provider>
      </ThemeProvider>
...

我比像这样拥有一个calendar.stories.js:

import { storiesOf } from '@storybook/react'
import { CalendarComponent } from "./Calendar"
import { formatAvailabilitiesData } from '../../__mocks__/availabilities'
import { log } from 'util';
import {muiTheme} from 'storybook-addon-material-ui'
import theme from '../../theme'

const props = {
    selectedAvailablity: formatAvailabilitiesData[0],
    selectedDate: new Date('2019-07-24T07:00:00.000Z'),
    dateClick: () => null,
}

storiesOf("Calendar", module)
  .addDecorator(muiTheme([PeabodyTheme]))
  .add("Basic", () => ( 
    <CalendarComponent {...props} />
))

和故事书的webpack文件,如下所示:

const path = require('path');

// Export a function. Accept the base config as the only param.
module.exports = async ({ config, mode }) => {
  // `mode` has a value of 'DEVELOPMENT' or 'PRODUCTION'
  // You can change the configuration based on that.
  // 'PRODUCTION' is used when building the static version of storybook.

  // Make whatever fine-grained changes you need
  config.module.rules.push(
  { 
    test: /\.(ttf|eot|svg)(\?[a-z0-9#=&.]+)?$/, 
    loaders: ["file-loader"] 
  });

  // Return the altered config
  return config;
};

字体在应用程序中正确显示,但在故事书中未正确显示。我尝试导入一些本地CSS以及字体家族作品以外的所有内容,这使我认为这与字体的加载有关。控制台中也没有错误。

更新

我什至试图像这样直接在组件内导入CSS:

@font-face {
  font-family: 'Poppings';
  src: url('../../assets/fonts/Poppins-Regular.ttf')
}

h2 {
  font-family: 'Poppings'; 
}

尽管这次实际上是在网络标签中加载了字体,但故事书组件h2并未继承自定义字体。...

1 个答案:

答案 0 :(得分:0)

我建议如下:

  1. 如果这些是本地字体,则忽略:为字体创建一个 css 文件,在其中只为字体定义 @font-face。
  2. 在您的 Storybook 配置所在的位置创建一个文件 preview-head.html,即 .storybook
  3. 在此文件中,为链接标签中包含字体外观定义的 css 文件各添加一行,例如:
<!-- local fonts -->
<link rel="stylesheet" href="./fonts/fonts.css" />

<!-- external font (I just copied the code for a random font from Google -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Castoro:ital@1&display=swap" rel="stylesheet">