Imports SVGs as source code, base64 and data URI. Preserves stroke width, replaces colors with currentColor. Optimizes SVGs with SVGO. Creates SVG sprites.
Installations
npm install vite-awesome-svg-loader
Developer Guide
Typescript
Yes
Module System
CommonJS, ESM
Node Version
18.20.5
NPM Version
10.8.2
Score
54
Supply Chain
89.4
Quality
86
Maintenance
100
Vulnerability
79.9
License
Releases
Major performance improvements
Published on 08 Jan 2025
Granular control over transforms, bug fixes, better demos
Published on 06 Jan 2025
React: fixed broken SvgImage lifecycle
Published on 18 Apr 2024
Fixed "Empty string passed to getElementById()"
Published on 15 Apr 2024
Fixed set-current-color not setting currentColor to elements with default black fill
Published on 06 Mar 2024
Fixed "false" query params being overridden by config
Published on 21 Feb 2024
Contributors
Unable to fetch Contributors
Languages
TypeScript (65.43%)
Vue (17.01%)
HTML (8.93%)
SCSS (5.56%)
JavaScript (2.96%)
CSS (0.11%)
Developer
matafokka
Download Statistics
Total Downloads
8,349
Last Day
58
Last Week
174
Last Month
1,298
Last Year
7,648
GitHub Statistics
13 Stars
68 Commits
1 Watching
2 Branches
1 Contributors
Bundle Size
766.38 kB
Minified
232.09 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.4.1
Package Id
vite-awesome-svg-loader@1.4.1
Unpacked Size
316.36 kB
Size
72.09 kB
File Count
26
NPM Version
10.8.2
Node Version
18.20.5
Publised On
08 Jan 2025
Total Downloads
Cumulative downloads
Total Downloads
8,349
Last day
7.4%
58
Compared to previous day
Last week
-42%
174
Compared to previous week
Last month
109.7%
1,298
Compared to previous month
Last year
991%
7,648
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
1
vite-awesome-svg-loader
A Vite plugin that:
- Can import SVGs as:
- Can preserve line width, i.e. make icons and line art have same line width when scaling.
- Can replace colors with
currentColor
. - Will minimize your SVGs using SVGO.
- Allows you to create SVG sprites using provided integrations.
vite-awesome-svg-loader
is framework-agnostic. All integrations are done in form of subpath imports (for example, vite-awesome-svg-loader/vue-integration
). This means that you'll get only what you need in your app bundle. This also means that you can develop your own integration using vite-awesome-svg-loader/integration-utils
import.
Examples and demos
Usage
- Grab this plugin from NPM:
npm i vite-awesome-svg-loader
. - Add it to
vite.config.js
orvite.config.ts
(whatever you use):
1import { defineConfig } from "vite"; 2import vue from "@vitejs/plugin-vue"; 3 4// Import vite-awesome-svg-loader 5import { viteAwesomeSvgLoader } from "vite-awesome-svg-loader"; 6 7export default defineConfig({ 8 plugins: [ 9 vue(), // Or whatever framework you're using 10 viteAwesomeSvgLoader(), // This plugin 11 // Other plugins... 12 ], 13 // Rest of the configuration... 14});
-
Optional, TypeScript only. Add some (unfortunately, it's impossible to implement all) of the import types to make TypeScript happy:
- Create
env.d.ts
file or use existing file where you store triple slash directives. - Add following string to it:
/// <reference types="vite-awesome-svg-loader" />
. - Open
tsconfig.json
and addenv.d.ts
to theinclude
property:{ "include": ["env.d.ts"] }
.
- Create
-
Use it to import files:
1// Source code 2import imageSrc from "./path/to/image.svg"; 3 4// URL 5import imageUrl from "./path/to/image.svg?url"; 6 7// Source code Data URI 8import imageSrcDataUri from "./path/to/image.svg?source-data-uri"; 9 10// Base64 11import imageBase64 from "./path/to/image.svg?base-64"; 12 13// Base64 data URI 14import imageBase64DataUri from "./path/to/image.svg?base-64-data-uri"; 15 16// Preserve line width 17import imagePreWidthSrc from "./path/to/image.svg?preserve-line-width"; 18 19// Replace fill, stroke and stop-color with currentColor 20import imageCurColorSrc from "./path/to/image.svg?set-current-color"; 21 22// Mix and match. We need @ts-ignore here because it's impossible to generate types for all possible URLs. 23// It is recommended to configure paths to avoid putting @ts-ignore for every import and writing long URLs. 24// @ts-ignore 25import transformedImageUrl from "./path/to/image.svg?url&preserve-line-width&set-current-color"; 26 27// explicitly disable any parameter by setting it to false. This takes precedence over config. 28import initialLineWidthImageUrl from "./path/to/image.svg?url&preserve-line-width=false";
- Optional, but highly recommended. Configure loader, so you can import SVGs without URL parameters:
1viteAwesomeSvgLoader({
2 // Set default import type. "source" is the default value.
3 //
4 // Available values:
5 // source - load SVG source code.
6 // url - load URL pointing to the SVG file. Loader will generate that file for you.
7 // source-data-uri - Source code put into a data URI.
8 // base64 - SVG source code encoded in base64.
9 // base64-data-uri - SVG source code in base64 put into a data URI.
10 defaultImport: "source",
11
12 // A list of files or directories to preserve line width of.
13 preserveLineWidthList: [/config-demo\/preserve-line-width\//, /config-demo\/all\//],
14
15 // A list of files to skip while preserving line width. Overrides preserveLineWidthList.
16 skipPreserveLineWidthList: [/line-width-not-preserved\.svg/],
17
18 // A list of files or directories to preserve color of
19 setCurrentColorList: [/config-demo\/set-current-color\//, /config-demo\/all\//],
20
21 // A list of files to skip while replacing colors. Overrides setCurrentColorList.
22 skipSetCurrentColorList: [/colors-not-preserved\.svg/],
23
24 // A list of files to skip while transforming. File skip-transforms.svg is present in every directory.
25 skipTransformsList: [/skip-transforms\.svg/, /ignore-elements-orig\.svg/],
26
27 // A list of files to skip loading of. File skip-loading.svg is present in every directory.
28 skipFilesList: [/skip-loading\.svg/],
29
30 // A list of selectors to skip while preserving line width
31 skipPreserveLineWidthSelectors: [
32 // It can be a list of CSS selectors like this one. Every element in every file will be checked against it.
33 '*[data-original-line-width="true"], *[data-original-line-width="true"] *',
34
35 // Or it can be configured on per-file basis:
36 {
37 files: [/ignore-elements\.svg/, /some-other-file\.svg/],
38 selectors: ['*[data-original-line-width="true"], *[data-original-line-width="true"] *'],
39 },
40 ],
41
42 // These two options are not recommended due to architectural and performance considerations (see JSDoc):
43
44 // A list of selectors to skip while replacing colors. Same format as above.
45 skipSetCurrentColorSelectors: ['*[data-original-color="true"], *[data-original-color="true"] *'],
46
47 // A list of selectors to skip while transforming. Same format as above.
48 skipTransformsSelectors: ['*[data-no-transforms="true"], *[data-no-transforms="true"] *'],
49}),
- Optional. Use integrations to create sprite sheets. Or write your own integration.
Integrations
All integrations work only on client side. However, they won't break SSR.
Vanilla JS
Warning: do NOT use this package to create custom integrations, use vite-awesome-svg-loader/integration-utils
instead.
Make sure to check the docs.
- Import classes:
1import { 2 SvgImage, // Basically implements SVG sprites 3 SvgIcon, // Basic SVG icon that uses SvgImage class internally 4} from "vite-awesome-svg-loader/vanilla-integration";
- Import images:
1import imageSrc from "@/path/to/image.svg";
- Use classes:
1new SvgImage(imageSrc, "#my-container"); // Create an image and mount it to the element with "my-container" id.
2
3new SvgIcon(imageSrc, "#my-container") // Create an icon and mount it to the element with "my-container" id.
4 .setSize("24px") // Set 24px size
5 .setColor("red") // Set red color
6 .setColorTransition("0.3s ease-out"); // Set color transition
See full example: source, demo.
Vue 3
- Import components:
1import { 2 SvgImage, // Basically implements SVG sprites 3 SvgIcon, // Basic SVG icon that uses SvgImage component internally 4} from "vite-awesome-svg-loader/vue-integration";
- Import images:
1import imageSrc from "@/path/to/image.svg";
- Use components:
1<template> 2 <div class="main"> 3 <SvgImage :src="imageSrc" /> 4 5 <SvgIcon 6 :src="imageSrc" 7 size="24px" 8 color="red" 9 color-transition="0.3s ease-out" 10 /> 11 </div> 12</template>
See full example: source, demo.
React
- Import components:
1import { 2 SvgImage, // Basically implements SVG sprites 3 SvgIcon, // Basic SVG icon that uses SvgImage component internally 4} from "vite-awesome-svg-loader/react-integration";
- Import images:
1import imageSrc from "@/path/to/image.svg";
- Use components:
1export function MyComponent() { 2 return ( 3 <div class="main"> 4 <SvgImage src={imageSrc} /> 5 6 <SvgIcon 7 src={imageSrc} 8 size="24px" 9 color="red" 10 colorTransition="0.3s ease-out" 11 /> 12 </div> 13 ) 14}
See full example: source, demo.
Custom integration
- Import helper functions and styles:
1import "integration-utils/styles.css"; 2 3// There function will run only on client side. However, they won't break SSR. 4 5import { 6 onSrcUpdate, // Should be called when component is mounted, and source code is updated 7 onUnmount, // Should be called when component is unmounted 8} from "integration-utils";
-
Write your integration. Use vue-integration as an example.
-
Please, submit your integration in a PR. Or just create an issue and provide the source code if you don't have time or don't want to deal with this project's development process.
Additional information
What are loading/import types (url, source, etc)?
Let's see how we can load SVGs, and what tradeoffs do they have:
- Put whole SVG source code into the DOM every time image is displayed. This is the most popular method.
- Advantages:
- Simplicity.
- Great customization. This is actually the only option, if you need to manipulate the content, or need more than just CSS styles.
- Disadvantages:
- Very bad performance. Browser needs to parse and update good number of DOM nodes. It doesn't really matter when images count is low, but it may slow down the page when 1000+ images are used. Another loading method is always preferred when customization is not required.
- Advantages:
- Link an image like so:
<img href="/image.svg">
orbackground-image: url("/image.svg")
.- Advantages:
- Simplicity.
- Great performance thanks to instancing.
- Disadvantages:
- Lack of any customization, good only for static images. You can't modify external assets using JS or CSS. The only thing you can do is filters. Note: don't try to implement icons this way. Browsers implement filters incorrectly, it's impossible to write 100% correct color to filter conversion function. This discrepancies are often way off the desired result. If you try to fix them, you'll lose all performance benefits. Trust me, I've tried implementing such system, wasted a lot of time and horribly failed.
- Advantages:
- Symbols: put all images into a single
<svg>
node and wrap each image with a<symbol>
element.- Advantages:
- Performance is way better than when using whole SVG each time.
- Images can be customized via CSS, for example, you can set custom stroke and fill colors.
- Disadvantages:
- Requires a bit of maintenance in form of using provided integrations.
- Performance is worse than when linking an image.
- Customization is not that great when using whole SVG source code.
- Advantages:
- Data URI: either use source code or base64 in a data URI.
- Advantages:
- Great performance, although a tiny bit worse than when linking an image.
- Disadvantages:
- Lack of any customization, good only for static images.
- Increased memory and traffic usage when linking images.
- Advantages:
To summarize:
- If you don't need customization, i.e. you want to display static images, use linking method.
- If you only need CSS customization, use symbols. This is preferred option for icons and line art that's needed to be customized.
- If you need heavy customization and interactivity, put whole SVG source code into the DOM.
- As for the data URI, not sure why you would need it. It's implemented just for completeness sake. If you have a use for it, please, notify me.
Can this loader put whole SVG source code every time I use an image?
Yes, load an image as a source code and insert that code into the DOM like shown in the demos.
Should I always import my images like shown in the examples? Can I simplify this?
Yes, use import.meta.glob()
like shown in the demos.
Such components are not present in the integrations because glob imports do not support variable interpolation. See: https://vitejs.dev/guide/features#glob-import
Note: if you want to support browsers without ES modules, use @vitejs/plugin-legacy as shown in the demos.
Comparison with other loaders
Implements a portion vite-awesome-svg-loader
functionality. This loader can also import SVGs as Vue components.
Due to framework-agnostic nature of vite-awesome-svg-loader
and relative simplicity of outputting raw HTML, this task is delegated to the user, and can be done as easy as you would with vite-svg-loader as shown in the Vue demo:
1<template> 2 <div v-html="imageSrc" /> 3</template> 4 5<script lang="ts" setup> 6import imageSrc from "./path/to/image.svg"; 7</script>
Similar approach can be applied to any other framework or vanilla JS.
@poppanator/sveltekit-svg, vite-plugin-react-svg, @svgx/vite-plugin-react, rollup-plugin-svelte-svg, vite-plugin-solid-svg and many more
Same as above, but for other frameworks.
vite-plugin-svg-icons, vite-plugin-magical-svg, vite-plugin-svg-sprite
Implements a portion vite-awesome-svg-loader
functionality.
Other loaders and plugins
Same as above. If your loader is different, and you want it to get roasted, or if it kills vite-awesome-svg-loader
, please, let the community know by creating an issue :p
How can I help?
- Create an integration with your favorite framework.
- Add new functionality to the loader itself.
- Report bugs.
- Create feature requests by creating an issue.
I want to participate in vite-awesome-svg-loader development. Where do I start?
Start by reading README_DEV.md. Then go on and do your thing :)
No vulnerabilities found.
No security vulnerabilities found.