nuxt3-svg-sprite-builder
v1.0.7
Published
Nitro plugin to inject SVG sprite from SVG files into your HTML
Downloads
181
Maintainers
Readme
nuxt3-svg-sprite-builder
Nitro plugin to inject SVG sprite from SVG files into your HTML
⚠️ This is experimental and currently only provided for testing and feedback. Use at your own risk!
From
📁 svg
├ 📁 icons
│ └ 📄 user.svg
├ 📁 illustrations
│ └ 📄 error.svg
└ 📄 logo.svg
To
<body>
<svg xmlns="http://www.w3.org/2000/svg" style="position: absolute; width: 0; height: 0;" aria-hidden="true">
<symbol id="icons/user" ...>...</symbol>
<symbol id="illustrations/error" ...>...</symbol>
<symbol id="logo" ...>...</symbol>
</svg>
...
</body>
Table of contents
Why it was made
- Popular modules like JetBrains/svg-sprite-loader do not support Vite as they are made for Webpack only.
- Vite modules based on Vite's
transformIndexHtml
hook do not work as it is not supported in Nuxt 3 (Issue #1711) - Most of modules bake in unwanted global components and require you to use them in order to use their module.
Installation
Install module via npm:
npm install nuxt3-svg-sprite-builder
Create svgSpriteBuilder.js
into /server/plugins
and add the following code:
import { svgSpriteBuilder } from 'nuxt3-svg-sprite-builder';
export default svgSpriteBuilder('./path/to/svg/folder');
Edit ./path/to/svg/folder
to match your SVG folder, default is ./assets/svg
if omitted.
Usage
Rendering an SVG
Render /svgDirectory/logo.svg
<svg>
<use href="#logo" />
</svg>
Render /svgDirectory/icons/user.svg
<svg>
<use href="#icons/user" />
</svg>
Creating a dynamic SVG component
/components/SvgComponent.vue
<template>
<svg>
<use :href="`#{href}`" />
</svg>
</template>
<script setup>
defineProps({
href: {
type: String,
required: true,
},
});
</script>
Dynamic SVG component usage
<SvgComponent :href="dynamicValue" />
Credits
- @Lstmxx for creating vite-svg-plugin on which this module is based on