Skip to content

Lucide Astro

Astro 组件,为 Lucide 图标提供完美兼容 Astro 的岛屿架构与多框架支持。每个图标都是一个 Astro 组件,渲染为内联 SVG,为静态站点和服务器端渲染场景提供卓越性能。

你可以实现的功能:

  • 以 Astro 组件的形式使用图标,零 JavaScript 运行时开销
  • 快速构建静态网站,使用优化后的 SVG 图标
  • 与 Astro 的组件岛屿和部分水化无缝集成
  • 构建跨多框架应用,图标在不同 UI 库中无缝工作
  • 通过直接导入图标和构建时渲染来优化性能

安装

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

如何使用

Lucide 使用 ES Modules 构建,因此完全可进行树摇优化。

每个图标均可作为 Astro 组件导入,渲染为内联 SVG 元素。这样,只有项目中实际导入的图标会包含在最终包中,其余图标将被树摇。

默认用法:

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

<Skull />

可传递附加属性以调整图标:

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

nametypedefault
sizenumber24
colorstringcurrentColor
stroke-widthnumber2
absoluteStrokeWidthbooleanfalse

应用属性

要定制图标的外观,可以直接将自定义属性作为 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(https://github.com/lucide-icons/lucide-lab)是一系列不属于 Lucide 主库的图标。

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

使用 Icon 组件

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,较大的 bundle 可能会导致冷启动变慢。

图标组件示例

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" />