簡體   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