unocss icons 使用图标预设

9,806 阅读2分钟

这是我参与11月更文挑战的第10天,活动详情查看:2021最后一次更文挑战

背景

如果你愿意了解 Unocss Icon 的原理,你可以阅读原文 聊聊纯 CSS 图标

本文文字营养不高,可以直接跳过到 -- 使用部分。


如果你的项目已经使用到了unocss,并且具有icon的需求,你可以轻量级的在项目使用unocss提供的图标预设。

可能大家在最早之前使用 icon 都是在 阿里巴巴矢量图标库里面进行选择使用,但是我们新增图标时,我们首先进行选择在更新它的 CSS ,再去对 (::befor, ::after)进行更改。这样即麻烦,同时也增加了许多的局限性。使用这种方案意味着你需要对 CSS 工作原理有深刻的理解,但同时也很难创造更为复杂的图标(只有3个元素可以使用)。

后来可能也是大家用的相对多的是,在项目中引用图标库,通过组件的形式进行使用

// import
import { Icon } from 'someIconsName'

// usage
<Icon />

使用方式也很简单,某些图标库也做到按需加载。也是很不错的使用方式。 我们以naive-ui的图标组件为例,看一下编译结果:

image.png

本质还是使用svg格式构建的图标。

但是 Unocss 采用的是纯 css 构建的图标库。 我们先来看看如何使用的把,再去探索一下源码的解析过程

使用

install

npm i -D @unocss/preset-icons @iconify-json/[the-collection-you-want]

你们到npm上面看一下 @iconify-json包,它底下有很多的子模块也进行包的发布。我们使用哪一个包,就是我们对应的collection名称

例如 我们安装:

npm i -D @iconify-json/carbon

配置

回到我们的unocss.config.ts

import { presetIcons, defineConfig } from 'unocss'

export const createConfig = () => {
  return defineConfig({
    presets: [
      // ...
      presetIcons({
        collections: {
          carbon: () =>
            import('@iconify-json/carbon').then((i) => i.icons as any)
        }
      })
    ]
  })
}

export default createConfig()

我们需要在presetIcons进行配置。collections中配置我们安装的carbon图标库,并且动态引入carbon包下的json(这个json存放的就是每一个图标的样式)

当然presetIcons中的配置不止collections

export interface Options {
  scale?: number // 缩放倍数 默认为1
  mode?: 'mask' | 'background-img' | 'auto'  // 模式 默认auto
  prefix?: string // 使用前缀 默认 `i-`
  warn?: boolean
  collections?: Record<string, IconifyJSON | undefined | (() => Awaitable<IconifyJSON | undefined>)>
  extraProperties?: Record<string, string> // 核外的属性,你可以书写额外的css属性到图标组件上
  /**
   * Rule layer
   * @default 'icons'
   */
  layer?: string
}

使用

上面配置好了就可以使用了。

<div m2 f-c hover="op80">
  <a i-carbon-logo-github text-3xl text-white href="https://github.com/chris-zhu" target="_blank" />
  <div i-carbon:3d-cursor text-3xl text-white />
  <button text-white text-3xl class="i-carbon-sun" />
</div>

image.png

image.png

image.png