Skip to content

Lucide Astro

Lucide 图标库在 Astro 应用中的实现。

安装

sh
pnpm add @lucide/astro
sh
yarn add @lucide/astro
sh
npm install @lucide/astro
sh
bun add @lucide/astro

使用方法

Lucide 使用 ES Modules 构建,因此完全支持 tree-shaking。

每个图标都可以作为 Astro 组件导入,它会渲染一个内联 SVG 元素。这样,只有导入到项目中的图标才会包含在最终捆绑包中。其余图标会被 tree-shake 掉。

示例

默认用法:

astro
---
import { Skull } from '@lucide/astro';
---

<Skull />

可以传递额外的 props 来调整图标:

astro
---
import { Camera } from '@lucide/astro';
---

<Camera color="#ff3e98" />

为了更快地构建和加载时间,您可以直接从 @lucide/astro/icons 目录导入图标:

astro
---
import CircleAlert from '@lucide/astro/icons/circle-alert';
---

<CircleAlert color="#ff3e98" />

Props

名称类型默认值
sizenumber24
colorstringcurrentColor
stroke-widthnumber2
absoluteStrokeWidthbooleanfalse

应用 props

要自定义图标的外观,您可以直接将自定义属性作为 props 传递给组件。组件接受所有 SVG 属性作为 props,这允许灵活地样式化 SVG 元素。请参阅 MDN 上的 SVG 表示属性列表。

astro
---
import { Phone } from '@lucide/astro';
---

<Phone fill="#333" />

这将生成一个填充的电话图标。

类型

该包包含所有图标的类型定义。如果您想动态渲染图标,这将非常有用。

示例

astro
---
import { House, Library, Cog, type Icon as IconType } from '@lucide/astro';

type MenuItem = {
  name: string;
  href: string;
  icon: typeof IconType;
};

const menuItems: MenuItem[] = [
  {
    name: 'Home',
    href: '/',
    icon: House,
  },
  {
    name: 'Blog',
    href: '/blog',
    icon: Library,
  },
  {
    name: 'Projects',
    href: '/projects',
    icon: Cog,
  },
];
---

{
  menuItems.map((item) => (
    <a href={item.href}>
      <item.icon />
      <span>{item.name}</span>
    </a>
  ))
}

与 Lucide lab 或自定义图标一起使用

Lucide lab 是一组不属于 Lucide 主库的图标集合。

它们可以通过使用 Icon 组件来使用。常规 Lucide 图标的所有 props 都可以传递以调整图标外观。

使用 Icon 组件

这会基于传递的 iconNode 创建单个图标,并渲染一个 Lucide 图标组件。

astro
---
import { Icon } from '@lucide/astro';
import { burger, sausage } from '@lucide/lab';
---

<Icon iconNode={burger} />
<Icon iconNode={sausage} color="red"/>

一个通用图标组件

可以创建一个通用图标组件来加载图标,但不推荐这样做。

DANGER

下面的示例会导入所有 ES Modules,因此在使用时请谨慎。导入所有图标会显著增加应用程序的构建大小。如果您在服务器环境中进行 SSG 和 SSR,这可能可以接受。但是,如果您在无服务器环境中进行 SSR,则可能会负面影响应用程序的性能,因为更大的捆绑包大小会导致冷启动时间增加。

图标组件示例

astro
---
import { icons, type IconProps } from '@lucide/astro';

interface Props extends IconProps {
  name: keyof typeof icons;
}

const { name, ...restProps } = Astro.props;
const Icon = icons[name];
---

<Icon {...restProps} />

使用图标组件

astro
---
import LucideIcon from './LucideIcon.astro';
---

<LucideIcon name="Menu" />