unplugin-icons vue3自动引入icon

17,513 阅读1分钟

安装

pnpm add -D unplugin-icons

配置

vite.config.ts配置:

import Icons from "unplugin-icons/vite";

plugins:[
    Icons({
      autoInstall: true,
      compiler: "vue3",
    }),
]

支持的配置

Icons({
  scale: 1.2, // Scale of icons against 1em
  defaultStyle: '', // Style apply to icons
  defaultClass: '', // Class names apply to icons
  compiler: null, // 'vue2', 'vue3', 'jsx'
  jsx: 'react' // 'react' or 'preact'
})

image.png

使用

icones.netlify.app/网站上找到想使用的图标 点击下图所示的按钮,即可复制图标,如下图,当前查看的是Element-plus的图标

image.png

image.png

Icon图标自动引入

这里需要配合unplugin-vue-components组件使用。

地址:github.com/antfu/unplu…

配置

import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import Components from 'unplugin-vue-components/vite'


  plugins: [
    Components({
      resolvers: [
        IconsResolver({
          prefix: 'icon', // 自动引入的Icon组件统一前缀,默认为 i,设置false为不需要前缀
          // {prefix}-{collection}-{icon} 使用组件解析器时,您必须遵循名称转换才能正确推断图标。
          // alias: { park: 'icon-park' } 集合的别名
          enabledCollections: ['ep'] // 这是可选的,默认启用 Iconify 支持的所有集合['mdi']
        }),
      ]
    }),
    Icons({
      // scale: 1, // 缩放
      compiler: 'vue3', // 编译方式
      // defaultClass: '', // 默认类名
      // defaultStyle: '', // 默认样式
      autoInstall: true
      // jsx: 'react' // jsx支持
    }),
  ],

使用

image.png

注:使用Icon自动引入,不需要下载图标库,系统会自动按需下载。

image.png

<IconEpFold class="v-icon" />
<icon-ep-fold class="v-icon" />
.v-icon {
  display: inline-block;
  width: 1em;
  height: 1em;
  font-size: 1em;
}

.v-icon>svg {
  width: 100%;
  height: 100%;
}

image.png