2.0.1 • Published 6 months ago

@lordbeanbag/vite-plugin-svg-icons-monorepo v2.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

vite-plugin-svg-icons

中文 | English

用于生成 svg 雪碧图.

特征

  • 预加载 在项目运行时就生成所有图标,只需操作一次 dom
  • 高性能 内置缓存,仅当文件被修改时才会重新生成

安装

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 { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'

export default () => {
  return {
    plugins: [
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',

        /**
         * 自定义插入位置
         * @default: body-last
         */
        inject?: 'body-last' | 'body-first'

        /**
         * custom dom id
         * @default: __svg__icons__dom__
         */
        customDomId: '__svg__icons__dom__',
      }),
    ],
  }
}
  • 在 src/main.ts 内引入注册脚本
import 'virtual:svg-icons-register'

到这里 svg 雪碧图已经生成

如何在组件使用

Vue 方式

/src/components/SvgIcon.vue

<template>
  <svg aria-hidden="true">
    <use :xlink:href="symbolId" :fill="color" />
  </svg>
</template>

<script>
import { defineComponent, computed } from 'vue'

export default defineComponent({
  name: 'SvgIcon',
  props: {
    prefix: {
      type: String,
      default: 'icon',
    },
    name: {
      type: String,
      required: true,
    },
    color: {
      type: String,
      default: '#333',
    },
  },
  setup(props) {
    const symbolId = computed(() => `#${props.prefix}-${props.name}`)
    return { symbolId }
  },
})
</script>

icons 目录结构

# src/icons

- icon1.svg
- icon2.svg
- icon3.svg
- dir/icon1.svg

/src/App.vue

<template>
  <div>
    <SvgIcon name="icon1"></SvgIcon>
    <SvgIcon name="icon2"></SvgIcon>
    <SvgIcon name="icon3"></SvgIcon>
    <SvgIcon name="dir-icon1"></SvgIcon>
  </div>
</template>

<script>
import { defineComponent, computed } from 'vue'

import SvgIcon from './components/SvgIcon.vue'
export default defineComponent({
  name: 'App',
  components: { SvgIcon },
})
</script>

React 方式

/src/components/SvgIcon.jsx

export default function SvgIcon({
  name,
  prefix = 'icon',
  color = '#333',
  ...props
}) {
  const symbolId = `#${prefix}-${name}`

  return (
    <svg {...props} aria-hidden="true">
      <use href={symbolId} fill={color} />
    </svg>
  )
}

获取所有 SymbolId

import ids from 'virtual:svg-icons-names'
// => ['icon-icon1','icon-icon2','icon-icon3']

配置说明

参数类型默认值说明
iconDirsstring[]-需要生成雪碧图的图标文件夹
symbolIdstringicon-[dir]-[name]svg 的 symbolId 格式,见下方说明
svgoOptionsboolean|SvgoOptionstruesvg 压缩配置,可以是对象Options
injectstringbody-lastsvgDom 默认插入的位置,可选body-first
customDomIdstring__svg__icons__dom__svgDom 插入节点的 ID

symbolId

icon-[dir]-[name]

name:

svg 文件名

dir

该插件的 svg 不会生成 hash 来区分,而是通过文件夹来区分.

如果iconDirs对应的文件夹下面包含这其他文件夹

例:

则生成的 SymbolId 为注释所写

# src/icons
- icon1.svg # icon-icon1
- icon2.svg # icon-icon2
- icon3.svg # icon-icon3
- dir/icon1.svg # icon-dir-icon1
- dir/dir2/icon1.svg # icon-dir-dir2-icon1

Typescript 支持

如果使用 Typescript,你可以在tsconfig.json内添加

// tsconfig.json
{
  "compilerOptions": {
    "types": ["vite-plugin-svg-icons/client"]
  }
}

注意

虽然用文件夹来区分已经可以很大程度避免重名问题了,但是也会出现iconDirs包含多个文件夹,且文件名一样的 svg.

这个需要开发者自己规避下

示例

运行示例

pnpm install
cd ./packages/playground/basic
pnpm run dev
pnpm run build

示例项目

Vben Admin

License

MIT © Vben-2020

JSONStreamacornacorn-jsxacorn-walkadd-streamaggregate-errorajvansi-escapesansi-regexansi-stylesany-promiseanymatchargargparsearr-diffarr-flattenarr-unionarray-ifyarray-unionarray-uniquearrifyassertion-errorassign-symbolsastral-regexasyncatobbalanced-matchbasebasic-authbig.jsbinary-extensionsbluebirdboolbasebrace-expansionbracesbrowserslistbuiltin-modulesbundle-requirecaccache-basecachedircall-bindcallsitescamelcasecamelcase-keyscaniuse-litechaichalkchardetcheck-errorchokidarclass-utilsclean-stackcli-cursorcli-truncatecli-widthcliuiclonecollection-visitcolor-convertcolor-namecolorettecommandercommondircompare-funccomponent-emitterconcat-mapconsolaconventional-changelogconventional-changelog-angularconventional-changelog-atomconventional-changelog-codemirrorconventional-changelog-conventionalcommitsconventional-changelog-coreconventional-changelog-emberconventional-changelog-eslintconventional-changelog-expressconventional-changelog-jqueryconventional-changelog-jshintconventional-changelog-preset-loaderconventional-changelog-writerconventional-commit-typesconventional-commits-filterconventional-commits-parserconvert-source-mapcopy-descriptorcore-util-iscorscorsercosmiconfigcosmiconfig-typescript-loadercreate-requirecross-spawncss-selectcss-treecss-whatcssocsstypecz-conventional-changelogdargsdateformatdebugdecamelizedecamelize-keysdecode-uri-componentdedentdeep-eqldeep-isdeepmergedefine-propertydefudetect-filedetect-indentdiffdir-globdoctrinedom-serializerdomelementtypedomhandlerdomutilsdot-propeastasianwidthelectron-to-chromiumemoji-regexemojis-listentitieserror-exes-module-lexeresbuildesbuild-linux-64escaladeescape-string-regexpeslint-scopeeslint-utilseslint-visitor-keysespreeesqueryesrecurseestraverseestree-walkeresutilsetageventemitter3execaexpand-bracketsexpand-tildeextend-shallowexternal-editorextglobfast-deep-equalfast-globfast-json-stable-stringifyfast-levenshteinfastqfiguresfile-entry-cachefill-rangefind-node-modulesfind-rootfind-upfindup-syncflat-cacheflattedfollow-redirectsfor-infragment-cachefs-extrafs.realpathfunction-bindfunctional-red-black-treegensyncget-caller-fileget-func-nameget-intrinsicget-pkg-repoget-streamget-valuegit-raw-commitsgit-remote-origin-urlgit-semver-tagsgitconfiglocalglobglob-parentglobal-dirsglobal-modulesglobal-prefixglobalsglobbygraceful-fshandlebarshard-rejectionhashas-ansihas-flaghas-symbolshas-valuehas-valueshash-sumhehomedir-polyfillhookablehosted-git-infohtml-encoding-snifferhtml-tagshtmlparser2http-proxyhttp-serverhuman-signalsiconv-liteignoreimage-sizeimport-freshimurmurhashindent-stringinflightinheritsiniinquireris-accessor-descriptoris-arrayishis-binary-pathis-bufferis-core-moduleis-data-descriptoris-descriptoris-extendableis-extglobis-fullwidth-code-pointis-globis-moduleis-numberis-objis-plain-objis-plain-objectis-referenceis-streamis-text-pathis-utf8is-windowsisarrayisexeisobjectjitijoyconjs-base64js-tokensjs-yamljsescjson-parse-better-errorsjson-parse-even-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjson-stringify-safejson5jsonc-parserjsonfilejsonparsekind-oflevnlilconfiglines-and-columnslistr2load-json-fileloader-utilslocal-pkglocate-pathlodashlodash.ismatchlodash.maplodash.mergelog-updatelongestloupelru-cachemagic-stringmake-errormap-cachemap-objmap-visitmdn-datameowmergemerge-optionsmerge-streammerge2micromatchmimemimic-fnmin-indentminimatchminimistminimist-optionsmixin-deepmkdirpmkdistmllymodify-valuesmrimsmute-streammznanoidnanomatchnatural-compareneo-asyncnode-releasesnormalize-package-datanormalize-pathnpm-run-pathnth-checkobject-assignobject-copyobject-inspectobject-visitobject.pickonceonetimeopeneroptionatoros-tmpdirp-limitp-locatep-mapp-tryparent-moduleparse-jsonparse-passwdpascalcasepath-existspath-is-absolutepath-keypath-parsepath-typepathepathvalpicocolorspicomatchpifypiratespkg-typesportfinderposix-character-classespostcsspostcss-load-configpostcss-prefix-selectorposthtmlposthtml-parserposthtml-rename-idposthtml-renderposthtml-svg-modeprelude-lspretty-bytesprocess-nextick-argspunycodeqqsquery-stringqueue-microtaskquick-lruread-pkgread-pkg-upreadable-streamreaddirpredentregex-notregexpprepeat-elementrepeat-stringrequire-directoryrequires-portresolveresolve-dirresolve-fromresolve-globalresolve-urlrestore-cursorretreusifyrfdcrolluprollup-plugin-dtsrollup-plugin-esbuildrun-asyncrun-parallelrxjssafe-buffersafe-regexsafer-buffersculesecure-comparesemverset-valueshebang-commandshebang-regexside-channelsignal-exitslashslice-ansisnapdragonsnapdragon-nodesnapdragon-utilsource-mapsource-map-jssource-map-resolvesource-map-urlsourcemap-codecspdx-correctspdx-exceptionsspdx-expression-parsespdx-license-idssplitsplit-stringsplit2stablestatic-extendstrict-uri-encodestring-argvstring-widthstring_decoderstrip-ansistrip-bomstrip-final-newlinestrip-indentstrip-json-commentssucrasesupports-colorsupports-preserve-symlinks-flagsvg-bakersvg-tagssvgotemp-dirtempfiletext-extensionstext-tablethenifythenify-allthroughthrough2tinypooltinyspytmpto-fast-propertiesto-object-pathto-regexto-regex-rangetraversetree-killtrim-newlinests-interface-checkerts-nodetslibtsutilstype-checktype-detecttype-festuglify-jsunionunion-valueuniversalifyunset-valueuntypeduri-jsurixurl-joinuseutil-deprecateuuidv8-compile-cachevalidate-npm-package-licensevaryvuewhatwg-encodingwhichword-wrapwordwrapwrap-ansiwrappyxtendy18nyallistyamlyargsyargs-parserynyocto-queue
2.0.1

6 months ago