我是webpack的新手,我正在尝试按照本教程https://medium.com/@mushti_dev/hey-e6faa20b910a
将自定义字体加载到stroybook v4中工作空间结构如下(create-react-app +故事书)
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;
};
preview-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>
Title.js
import React from 'react';
const Title = ({ title }) => {
return (
<div>
<h2 style={{fontFamily: 'MyCustomFont'}}>{title}</h2>
</div>
);
};
export default Title;
我的问题是如何从 fonts文件夹加载MyCustomFont.woff?
我尝试用name: 'fonts/[name].[ext]',
更新webpack配置,并用src: url('fonts/MyCustomFont.woff') format('woff');
更新css样式,但是我很难匹配正确的字体路径。
答案 0 :(得分:1)
我刚刚在 storybook v6.1
上遇到了这个问题,然后意识到实际上有两个字体区域需要设置:
preview-head.html
中的组件预览字体)manager-head.html
中的仪表板导航字体)我做了什么:
preview-head.html
并重命名为 manager-head.html
@font-face
确保 -s
中指定的字体 url 相对于 npm 脚本中指定的静态文件夹路径main.js
中更改 webpack 配置我的文件夹结构
|- .storybook/
|- ...
|- preview-head.html
|- manager-head.html
|- src/
|- ...
|- fonts/
|- font-name.otf
<块引用>
preview-head.html
和 manager-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"
}
}