You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在rollup打包组件库时通过css-modules引入@font-face字体

可行配置方案

你当前配置的问题是仅引入了postcss-url和注释了@rollup/plugin-url,但没有在对应的插件链中启用和配置这两个工具,导致字体资源未被识别打包。以下是可直接使用的修改后配置,提供两种常用策略:

  • 小字体推荐用base64内联模式:直接将字体写入css文件,无需额外输出字体资源,降低组件库接入成本
  • 大字体推荐用单独文件输出模式:将字体单独打包到产物目录,避免css体积过大

完整配置(内联模式,适配CSS Modules)

import babel from 'rollup-plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import postcss from 'rollup-plugin-postcss';
import resolve from '@rollup/plugin-node-resolve';
import image from '@rollup/plugin-image';
import typescript from 'rollup-plugin-typescript2';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import dts from 'rollup-plugin-dts';
import url from '@rollup/plugin-url'; // 取消原注释
import postcssUrl from 'postcss-url'; // 重命名避免和rollup的url插件冲突
import copy from 'rollup-plugin-copy';

import pkg from './package.json';

export default [
  {
    input: './src/index.ts',
    output: [
      {
        file: pkg.main,
        format: 'cjs',
        sourcemap: true,
      },
      {
        file: pkg.module,
        format: 'esm',
        sourcemap: true,
      },
    ],
    plugins: [
      peerDepsExternal(),
      resolve(),
      commonjs(),
      typescript({ useTsconfigDeclarationDir: true }),
      babel({
        exclude: 'node_modules/**',
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
      }),
      // 修改postcss配置
      postcss({
        modules: true, // 开启CSS Modules支持,可自定义modules规则
        plugins: [
          // 配置postcss-url将字体资源内联为base64
          postcssUrl({
            url: 'inline'
          })
        ]
      }),
      image(),
      // 新增rollup url插件处理字体文件
      url({
        // 匹配所有字体格式
        include: ['**/*.ttf', '**/*.woff', '**/*.woff2', '**/*.eot', '**/*.svg'],
        limit: Infinity, // 所有字体都内联,不单独输出文件
      })
    ],
  },
  {
    input: './types/index.d.ts',
    output: [{ file: './dist/mycomponents.d.ts', format: 'es' }],
    plugins: [dts()],
  },
];

若需单独输出字体文件,修改对应配置即可

// postcssUrl配置改为
postcssUrl({
  url: 'copy',
  assetsPath: 'fonts', // 字体输出到dist/fonts目录
  publicPath: './fonts/' // css中引用字体的路径前缀
})

// @rollup/plugin-url配置改为
url({
  include: ['**/*.ttf', '**/*.woff', '**/*.woff2', '**/*.eot', '**/*.svg'],
  limit: 0, // 所有字体都单独输出
  fileName: '[name][extname]',
  destDir: './dist/fonts'
})

验证方法

打包完成后查看dist目录下的css文件,@font-face的src属性会自动替换为base64编码串(内联模式)或正确的相对字体路径(单独输出模式),字体即可正常生效。

内容的提问来源于stack exchange,提问作者Sanne Wintrén

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 14:15:04