lucide 原生 JS 图标在 Web Components 的 Shadow DOM 中如何渲染?
【免费下载链接】lucideBeautiful & consistent icon toolkit made by the community. Open-source project and a fork of Feather Icons.项目地址: https://gitcode.com/GitHub_Trending/lu/lucide
在 Web Component 中,Shadow DOM 的内容与宿主页面隔离,直接往 document 上做的图标替换看不到它。Lucide 官方文档(Shadow DOM)明确说明:Lucide 图标可以在 shadow DOM 内使用。文档给出了原生 JavaScript(无框架)下的两种做法:用createElement创建单个图标并插入 shadow root,以及用createIcons批量替换 shadow root 内的<i>npm install lucide
等价的包管理命令(同一文档给出):pnpm add lucide、yarn add lucide、bun add lucide。
方式一:用createElement创建单个图标
官方示例代码(来自文档的在线沙箱,沙箱内置了lucide依赖和打包器):
index.html:
<!DOCTYPE html> <html> <body> <div id="container"></div> <script src="index.js"></script> </body> </html>index.js(在本地项目里即你的入口 JS 文件):
import { Home, createElement } from 'lucide/dist/cjs/lucide'; const container = document.getElementById('container'); const shadowRoot = container.attachShadow({ mode: 'open' }); const iconElement = createElement(Home) shadowRoot.appendChild(iconElement);步骤含义:
attachShadow({ mode: 'open' })在#container元素上取得 shadow root;createElement(Home)生成Home图标对应的图标元素;shadowRoot.appendChild(iconElement)把它插入 shadow DOM。
两处说明:
- 文档原代码中的
import "./styles.css";一行是沙箱模板自带的样式文件引入,与图标渲染无关,本地复现时删除即可; lucide/dist/cjs/lucide是文档沙箱使用的 CJS 入口;在常规打包项目里,按 Getting started 文档推荐用 ESM 形式导入:import { Home, createElement } from 'lucide';。
方式二:用createIcons批量渲染多个图标
要一次在 shadow DOM 里渲染多个图标,用createIcons的root选项指定 shadow root 作为替换范围。官方示例的index.html与方式一相同(#container结构),index.js为:
import { TreePalm, Volleyball, Waves, createIcons } from 'lucide/dist/cjs/lucide'; const container = document.getElementById('container'); const shadowRoot = container.attachShadow({ mode: 'open' }); const iconWrapper = document.createElement('div'); iconWrapper.innerHTML = ` <i contenteditable="false">【免费下载链接】lucideBeautiful & consistent icon toolkit made by the community. Open-source project and a fork of Feather Icons.
项目地址: https://gitcode.com/GitHub_Trending/lu/lucide创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考