Skip to content

Lucide

Lucide 图标库的 Web 应用实现。

安装

包管理器

sh
pnpm install lucide
sh
yarn add lucide
sh
npm install lucide
sh
bun add lucide

CDN

html
<!-- 开发版本 -->
<script src="https://unpkg.com/lucide@latest/dist/umd/lucide.js"></script>

<!-- 生产版本 -->
<script src="https://unpkg.com/lucide@latest"></script>

使用方法

使用 unpkg

以下是使用 unpkg 的完整示例

html
<!DOCTYPE html>
<body>
  <i data-lucide="volume-2" class="my-class"></i>
  <i data-lucide="x"></i>
  <i data-lucide="menu"></i>

  <script src="https://unpkg.com/lucide@latest"></script>
  <script>
    lucide.createIcons();
  </script>
</body>

使用 ES 模块

为了减少捆绑包大小,Lucide 被构建为完全可树摇的。 createIcons 函数将搜索具有 data-lucide 属性的 HTMLElements,并用给定图标名称的 SVG 替换它。

html
<!-- 您的 HTML 文件 -->
<i data-lucide="menu"></i>
js
import { createIcons, icons } from 'lucide';

// 注意,这将导入所有图标并捆绑它们。
createIcons({ icons });

// 推荐方式,仅包含您需要的图标。
import { createIcons, Menu, ArrowRight, Globe } from 'lucide';

createIcons({
  icons: {
    Menu,
    ArrowRight,
    Globe
  }
});

高级使用

附加选项

createIcons 函数中,您可以传递一些额外的参数:

  • 您可以传递 nameAttr 来调整要替换的属性名称
  • 您可以传递 attrs 来传递额外的自定义属性,例如 CSS 类或描边选项。
  • 您可以传递 root 来提供一个自定义的 DOM 元素,在其中替换图标(在操作大型 DOM 的小部分或 Shadow DOM 中的元素时很有用)

以下是一个完整示例:

js
import { createIcons } from 'lucide';

createIcons({
  attrs: {
    class: ['my-custom-class', 'icon'],
    'stroke-width': 1,
    stroke: '#333'
  },
  nameAttr: 'data-lucide', // 图标名称的属性。
  root: element, // 要替换图标的 DOM 元素。
});

树摇库,仅使用您使用的图标

js
import { createIcons, Menu, ArrowRight, Globe } from 'lucide';

createIcons({
  icons: {
    Menu,
    ArrowRight,
    Globe
  }
});

自定义元素绑定

js
import { createElement, Menu } from 'lucide';

const menuIcon = createElement(Menu); // 返回 HTMLElement (svg)

// 在 DOM 中追加 HTMLElement
const myApp = document.getElementById('app');
myApp.appendChild(menuIcon);

带自定义属性的自定义元素绑定

js
import { createElement, Menu } from 'lucide';

const menuIcon = createElement(Menu, {
  class: ['my-custom-class', 'icon'],
  'stroke-width': 1,
  stroke: '#333'
}); // 返回 HTMLElement (svg)

// 在 DOM 中追加 HTMLElement
const myApp = document.getElementById('app');
myApp.appendChild(menuIcon);

使用 Lucide lab 或自定义图标

Lucide lab 是一组不在 Lucide 主库中的图标集合。 它们可以以与官方图标相同的方式使用。

js
import { coconut } from '@lucide/lab';

createIcons({
  icons: {
    coconut
  }
});