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

能否向Heroicons库中添加自定义图标?

实现自定义图标像Heroicons一样使用的方案

1. 对齐Heroicons的目录结构与组件规范

Heroicons的核心体验在于「统一结构的组件+分类导出」,你可以完全模仿这个逻辑:

  • 创建custom-icons目录,按官方的风格分类(比如outline、solid)建立子目录
  • 将自定义SVG转换成和Heroicons结构一致的组件,以React版本为例:
    import React from 'react';
    
    const CustomStarIcon = ({ className = 'w-6 h-6', ...props }) => {
      return (
        <svg
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
          strokeWidth={1.5}
          stroke="currentColor"
          className={className}
          {...props}
        >
          {/* 替换成你的自定义SVG路径 */}
          <path strokeLinecap="round" strokeLinejoin="round" d="M11.48 3.499a.562.562 0 011.04 0l2.125 5.111a.563.563 0 00.475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 00-.182.557l1.285 5.385a.562.562 0 01-.84.61l-4.725-2.885a.563.563 0 00-.586 0L6.982 20.54a.562.562 0 01-.84-.61l1.285-5.386a.562.562 0 00-.182-.557l-4.204-3.602a.563.563 0 01.321-.988l5.518-.442a.563.563 0 00.475-.345L11.48 3.5z" />
        </svg>
      );
    };
    
    export default CustomStarIcon;
    
    重点保持和官方一致的props设计:默认className、支持透传属性、统一的SVG基础属性(stroke/fill规则)
  • 在各风格目录的index.js统一导出图标:
    // src/custom-icons/outline/index.js
    export { default as CustomStarIcon } from './CustomStarIcon';
    // 其他自定义图标依次导出
    
  • 最后在根目录custom-icons/index.js汇总所有风格:
    export * from './outline';
    export * from './solid';
    

2. 配置导入别名实现Heroicons式引用

通过构建工具配置别名,让导入路径和官方保持一致:

  • 若使用Vite,在vite.config.js中添加:
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    
    export default defineConfig({
      plugins: [react()],
      resolve: {
        alias: {
          '@heroicons/react/custom': '/src/custom-icons',
        },
      },
    });
    
    之后就能像导入官方图标一样使用:
    import { CustomStarIcon } from '@heroicons/react/custom/outline';
    

3. 批量转换SVG的快捷方式

如果有大量自定义SVG,用svgr批量生成符合规范的组件:

  • 先创建模板文件heroicon-template.js:
    function template({ componentName, jsx }) {
      return `import React from 'react';
    
    

const ${componentName} = ({ className = 'w-6 h-6', ...props }) => {
return (
${jsx}
);
};

export default ${componentName};
`;
}

module.exports = template;

- 执行批量转换命令:
```bash
npx @svgr/cli --template ./heroicon-template.js --out-dir src/custom-icons/outline src/custom-svgs/outline/

4. 非React环境的纯SVG方案

如果用纯SVG版Heroicons,把自定义SVG放到和官方图标相同的目录(比如public/icons/custom),引用方式和官方保持一致:

<img src="/icons/custom/outline/custom-star.svg" class="w-6 h-6" />

内容的提问来源于stack exchange,提问作者Luca Schönherr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 19:19:55