繁体   English   中英

如何配置 webpack 以将自定义字体加载到故事书中?

[英]How to config webpack to load custom fonts into storybook?

我是 webpack 的新手,我正在尝试按照本教程将自定义字体加载到 stroybook v4 https://medium.com/@mushti_dev/hey-e6faa20b910a

工作区结构如下所示(create-react-app + storybook)

my-project/
  .storybook
     config.js
     preview-hrad.html
     webpack.config.js
  fonts
    MyCustomFont.woff
  src
    components
       Title.js
    containers
    styles
       MyCustomFont.woff
    index.js
  stories

从src中的styles文件夹加载字体时,配置如下:

webpack.config.js

const path = require('path');

module.exports = async ({ config }) => {
  // fonts
  config.module.rules.push({
    test: /\.(png|woff|woff2|eot|ttf|svg)$/,
    use: [
      {
        loader: 'file-loader',
        query: {
          name: '[name].[ext]',
        }
      }
    ],
    include: path.resolve(__dirname, '../')
  });

  return config;
};

预览-head.html

<style type="text/css">
  @font-face {
    font-family: 'MyCustomFont';
    src: url('styles/MyCustomFont.woff') format('woff');
    font-weight: normal;
    font-style: normal;
  }
</style>

标题.js

import React from 'react';

const Title = ({ title }) => {
  return (
    <div>
      <h2 style={{fontFamily: 'MyCustomFont'}}>{title}</h2>
    </div>
  );
};

export default Title;

我的问题是如何从字体文件夹加载 MyCustomFont.woff ?

我尝试使用name: 'fonts/[name].[ext]',更新 webpack 配置name: 'fonts/[name].[ext]',并使用src: url('fonts/MyCustomFont.woff') format('woff'); css 样式src: url('fonts/MyCustomFont.woff') format('woff'); 但我很难匹配正确的字体路径。

我刚刚在storybook v6.1上遇到了这个问题,然后意识到实际上有两个字体区域需要设置:

  • iframe 预览字体(在preview-head.html组件预览字体)
  • 故事书仪表板字体( manager-head.html仪表板导航字体)

我做了什么:

  • 复制preview-head.html并重命名为manager-head.html
  • 确保@font-face指定的字体 url 相对于 npm 脚本中使用-s指定的静态文件夹路径
  • 我没有改变的WebPack配置在main.js

我的文件夹结构

|- .storybook/
   |- ...
   |- preview-head.html
   |- manager-head.html
|- src/
   |- ...
   |- fonts/
      |- font-name.otf

preview-head.htmlmanager-head.html

<style type="text/css">
  @font-face {
    font-family: 'font-name';
    src: url('fonts/font-name.otf') format('opentype');
    ...
  }
</style>

package.json

{
  ...
  "scripts": {
    ...
    "storybook": "start-storybook ... -s ./src",
    "build-storybook": "build-storybook -s ./src"
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM