如何在Storybook构建产物中包含自定义字体文件
Hey there! The core problem here is that Babel only processes JavaScript/TypeScript files by default—it doesn’t handle static assets like .ttf font files. That’s why your fonts aren’t showing up in the dist folder after running yarn build. Here are a few practical solutions to fix this:
1. Use the copyfiles Package (Recommended)
This is the easiest way to automate copying static assets during your build process:
- First, install the dev dependency:
yarn add -D copyfiles - Update your
buildscript inpackage.jsonto add a step that copies the font files right after Babel compiles your code:"scripts": { "build": "BABEL_ENV=production babel src -d dist && copyfiles -u 1 src/assets/fonts/*.ttf dist/assets/fonts/" }- The
-u 1flag removes the top-levelsrc/from the source path, so your fonts end up indist/assets/fonts/(matching your original directory structure). This ensures theurl()references in yourfontFacesCSS stay valid.
- The
2. Manual Copy (Quick Temporary Fix)
If you just need a quick test and don’t want to add a new package, you can manually copy the font files from src/assets/fonts/ to dist/assets/fonts/ after running your build command. Keep in mind this is tedious for repeated builds, so it’s not ideal for long-term use.
3. Switch to Webpack (If You’re Open to It)
If your project is using or planning to use Webpack (common for Storybook setups), you can configure it to handle font assets automatically:
- Use Webpack’s Asset Modules (no extra loaders needed in Webpack 5+) to emit font files to your
distfolder. Add this rule to your Webpack config:
This will automatically copy your fonts tomodule.exports = { module: { rules: [ { test: /\.(ttf)$/i, type: 'asset/resource', generator: { filename: 'assets/fonts/[name][ext]' } } ] } };dist/assets/fonts/when you run a Webpack build, and update the asset paths in your compiled code.
Just make sure after setting this up, you test your build to confirm the font paths in the compiled CSS point to the correct location in dist!
内容的提问来源于stack exchange,提问作者Kore

