Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Dynamically loads an SVG source and inline <svg> element so you can manipulate the style of it

License

NotificationsYou must be signed in to change notification settings

shrpne/vue-inline-svg

Repository files navigation

NPM PackageMinified SizeGzipped SizeLicense: MIT

Vue component loads an SVG source dynamically and inline<svg> so you can manipulate the style of it with CSS or JS.It looks like basic<img> so you markup will not be bloated with SVG content.Loaded SVGs are cached so it will not make network request twice.

Using Vue v2?

Check old versionvue-inline-svg@2

Install

NPM

npm install vue-inline-svg

Register locally in your component

importInlineSvgfrom'vue-inline-svg';// Your componentexportdefault{components:{        InlineSvg,}}

Or register globally in the Vue app

import{createApp}from'vue'importInlineSvgfrom'vue-inline-svg';constapp=createApp({/*...*/});app.component('inline-svg',InlineSvg);

Usually, registering components globally may be considered as bad practice, such it may pollute the main bundle, but since InlineSvg is a very small package and inlining icons may be needed throughout the whole app, registering globally may bring no to littledownsides but improve DX

CDN

<scriptsrc="https://unpkg.com/vue"></script><!-- Include the `vue-inline-svg` script on your page after Vue script --><scriptsrc="https://unpkg.com/vue-inline-svg"></script><script>constapp=Vue.createApp({/*...*/});app.component('inline-svg',VueInlineSvg);</script>

Usage

<InlineSvgsrc="image.svg"transformSource="transformSvg"@loaded="svgLoaded($event)"@unloaded="svgUnloaded()"@error="svgLoadError($event)"width="150"height="150"fill="black"aria-label="My image"/>

Example

Using relative paths or aliased paths

If you are referencing assets with relative path (not frompublic directory), e.g. "./assets/my.svg", "@/assets/my.svg", then@vitejs/plugin-vue or@vue/cli will not handle them automatically like they do for<img> tag, so you will need to manually import them with your bundler or configure automatic handling.

Configuring automatic handling with@vitejs/plugin-vue

// vite.config.jsimport{defineConfig}from'vite';importvuefrom'@vitejs/plugin-vue';exportdefaultdefineConfig({plugins:[vue({template:{transformAssetUrls:{// default optionsvideo:['src','poster'],source:['src'],img:['src'],image:['xlink:href','href'],use:['xlink:href','href'],// adding InlineSvg component with camel and kebab casingInlineSvg:['src'],['inline-svg']:['src'],},},}),],});
<!-- So this will work--><InlineSvgsrc="@/assets/img/my.svg"/>

Manual importing

<!-- vite --><script>importimgUrlfrom'@/assets/img/my.svg';</script><InlineSvg:src="imgUrl"/><!-- webpack --><InlineSvg:src="require('@/assets/img/my.svg')"/>

You might also likevite-plugin-require to enablerequire() in Vite.

Learn more about static assets handling:

props

-src

Type:stringRequired

Path to SVG file

<!-- from /public folder --><InlineSvgsrc="/my.svg"/><!-- from relative path --><InlineSvgsrc="./assets/img/my.svg"/><!-- from aliased path --><InlineSvgsrc="@/assets/img/my.svg"/><InlineSvgsrc="~/assets/img/my.svg"/>

Note on relative and aliased paths

-title

Type:string

Sets/overwrites the<title> of the SVG

<InlineSvgsrc="image.svg"title="My Image"/>

-uniqueIds

Type:boolean | string

Add suffix to all IDs in SVG to eliminate conflicts for multiple SVGs with the same source. Iftrue - suffix is random string, ifstring - suffix is this string.

<InlineSvgsrc="image.svg":uniqueIds="true"/><InlineSvgsrc="image.svg"uniqueIds="my-unique-suffix"/>

-uniqueIdsBase

Type:string

An URL to prefix each ID in case you use the<base> tag anduniqueIds.

<InlineSvgsrc="image.svg":uniqueIds="true"uniqueIdsBase="http://example.com""/>

-keepDuringLoading

Type:boolean; Default:true

It makes vue-inline-svg to preserve old image visible, when new image is being loaded. Passfalse to disable it and show nothing during loading.

<InlineSvgsrc="image.svg":keepDuringLoading="false"/>

-transformSource

Type:(svg: SVGElement) => SVGElement

Function to transform SVG content

This example create circle in svg:

<InlineSvgsrc="image.svg":transformSource="transform"/><script>consttransform=(svg)=>{letpoint=document.createElementNS("http://www.w3.org/2000/svg",'circle');point.setAttributeNS(null,'cx','20');point.setAttributeNS(null,'cy','20');point.setAttributeNS(null,'r','10');point.setAttributeNS(null,'fill','red');svg.appendChild(point);returnsvg;}// For cleaner syntax you could use https://github.com/svgdotjs/svg.js</script>

SVG attributes

Other SVG and HTML attributes will be passed to inlined<svg>. Except attributes withfalse ornull value.

<!-- input --><InlineSvgfill-opacity="0.25":stroke-opacity="myStrokeOpacity":color="false"/><!-- output --><svgfill-opacity="0.25"stroke-opacity="0.5"></svg>

events

-loaded

Called when SVG image is loaded and inlined.Inlined SVG element passed as argument into the listener’s callback function.

<InlineSvg@loaded="myInlinedSvg = $event"/>

-unloaded

Called whensrc prop was changed and another SVG start loading.

<InlineSvg@unloaded="handleUnloaded()"/>

-error

Called when SVG failed to load.Error object passed as argument into the listener’s callback function.

<InlineSvg@error="log($event)"/>

🛡️ Security Considerations

Inlining SVGs directly into the DOM provides flexibility for styling and interaction. However, it can pose risks of XSS (Cross-Site Scripting) attacks. SVGs can contain JavaScript (<script> tags), event handlers (onload,onclick, etc.), or external references (<use xlink:href="..."), which could be exploited.

To ensure security, follow these guidelines based on your SVG source:

1️⃣ SVGs from your project assets

Manually check they don't contain any harmful elements or attributes (scripts, event handlers, external references)

2️⃣ SVGs from third-party sources or user-generated content

Always sanitize before inlining. UseDOMPurify

<InlineSvgsrc="https://example.com/external.svg":transformSource="sanitize"/><script>importDOMPurifyfrom'dompurify';functionsanitize(svg){svg.innerHTML=DOMPurify.sanitize(svg.innerHTML,{USE_PROFILES:{svg:true}});returnsvg;}</script>

Alternative approaches

  • vite-svg-loader, webpack'svue-svg-loader. These tools embed SVG content directly into the JS bundle during compilation.Pros: SVG is bundled, eliminating the need for separate HTTP requests.Cons: Increased bundle size can delay the execution of more critical JS tasks. Additionally, each icon will be parsed multiple times: first as JS and then as HTML when inserted into the document (JS parsing is resource-intensive). Further reading on thecons of SVG-in-JS

  • The<svg><use href="my.svg#icon1"/></svg> approach requires no JS, that is great, but it has several disadvantages:

    • may be not very convenient, it requires referencing IDs, updating SVGfill's withcurrentColor. May be hard to manipulate other things except the main color. While DX can be improved with@svg-use
    • doesn't support cross-origin resources
    • doesn't support embedded<style>,<mask>,<clipPath>,<animate>,<animateMotion>,<animateTransform> tags
  • inlining withvue-inline-svg. As cons, it requires some JS, but very little, only for the component itself. Icons are loaded separately from the JS bundle, so they are not available instantly after JS is loaded, but it can also be seen as an advantage, as it leads to faster JS bundle load. Inlining offers maximum flexibility on par with SVG-in-JS. Overall, it has excellent DX: if the component will beregistered globally and automatic asset handling will beconfigured, then usage will be as easy as a simple<img>

Changelog

CHANGELOG.md

Contributing

CONTRIBUTING.md

License

MIT License

About

Dynamically loads an SVG source and inline <svg> element so you can manipulate the style of it

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors11


[8]ページ先頭

©2009-2025 Movatter.jp