svg特征
node version: >=12.0.0
vite version: >=2.0.0
- yarn add vite-plugin-svg-icons -D
- # or
- npm i vite-plugin-svg-icons -D
- # or
- pnpm install vite-plugin-svg-icons -D
vite.config.ts
- import { VantResolver } from 'unplugin-vue-components/resolvers'
- +import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
- +import path from 'path'
-
- // https://vitejs.dev/config/
- export default defineConfig({
- plugins: [
- vue(),
- Components({
- dts: false,
- resolvers: [VantResolver({ importStyle: false })]
- }),
- + createSvgIconsPlugin({
- + // 指定图标文件夹,绝对路径(NODE代码)
- + iconDirs: [path.resolve(process.cwd(), 'src/icons')]
- + })
- ],
目录结构
main.ts
import 'virtual:svg-icons-register'
- <svg aria-hidden="true">
-
- <use href="#icon-login-eye-off" />
- svg>
components/CpIcon.vue
-
- <template>
- <svg aria-hidden="true" class="cp-icon">
- <use :href="`#icon-${name}`" />
- svg>
- template>
-
- <style lang="scss" scoped>
- .cp-icon {
- // 和字体一样大
- width: 1em;
- height: 1em;
- }
- style>
提供使用时提示 类型 types/components.d.ts
- import CpIcon from '@/components/CpIcon.vue'
-
- declare module 'vue' {
- interface GlobalComponents {
- CpIcon: typeof CpIcon
- }
- }
提示:有些图标可以根据 style 中 color
的值来设置颜色,图标是否有这个功能取决于 UI 做图片时否开启
使用:
"login-eye-on">