Export SVG using Iconify Utils
This tutorial is part of code examples for Iconify Utils.
Export SVG
This is an example of using Iconify Utils to generate SVG from an icon set:
demo.ts
ts
// Import full icon set
import { icons } from '@iconify-json/mdi-light';
// Various functions from Iconify Utils
import { getIconData, iconToSVG, iconToHTML } from '@iconify/utils';
// Get ful data for 'mdi-light:home'
const iconData = getIconData(icons, 'home');
if (!iconData) {
throw new Error('Home icon does not exist');
}
// Generate data for rendering SVG
// Second optional parameter is customisations
const renderData = iconToSVG(iconData);
/*
Result of iconToSVG() can be used to either generate HTML code or to use in various components
renderData = {
attributes: {
width: '1em',
height: '1em',
viewBox: '0 0 24 24'
},
body: '<path d="M16 8.414l-4.5-4.5L4.414 11H6v8h3v-6h5v6h3v-8h1.586L17 9.414V6h-1v2.414zM2 12l9.5-9.5L15 6V5h3v4l3 3h-3v7.998h-5v-6h-3v6H5V12H2z" fill="currentColor"/>'
}
*/
// Generate SVG
const svg = iconToHTML(renderData.body, renderData.attributes);
// Log SVG
console.log(svg);
Async example
This is another example that:
- Uses asynchronous functions to parse icon sets.
- Uses @iconify/json as source.
- Written in modern JavaScript, not TypeScript.
demo.js
js
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { iconToSVG, iconToHTML, parseIconSetAsync } from '@iconify/utils';
import { locate } from '@iconify/json';
/**
* Dimensions of generated SVG:
* - '1em' -> 1em, easy to resize icons with font-size.
* - 'auto' -> same as icon's viewBox.
* - 'unset' -> no width/height in generated icons. You'll need to assign width and height in CSS.
*/
const height = '1em';
/**
* List of icon sets you want to export
*
* @type {string[]}
*/
const prefixes = ['mdi', 'mdi-light'];
/**
* Output directory for SVG
*/
const target = 'assets/svg';
// Parse each icon set
for (let i = 0; i < prefixes.length; i++) {
const prefix = prefixes[i];
// Find location of .json file
const filename = locate(prefix);
// Load file and parse it
/** @type {import("@iconify/types").IconifyJSON} */
const iconSet = JSON.parse(await readFile(filename, 'utf8'));
// Create output directory if it doesn't exist
const outDir = `${target}/${prefix}`;
try {
await mkdir(outDir, {
recursive: true,
});
} catch {}
// Get all icons
let counter = 0;
await parseIconSetAsync(iconSet, async (name, data) => {
if (!data) {
// Failed icon
return;
}
// Generate SVG
const { attributes, body } = iconToSVG(data, {
height,
});
const svg = iconToHTML(body, attributes);
// Save it
await writeFile(`${outDir}/${name}.svg`, svg, 'utf8');
counter++;
});
// Log it
console.log(`Exported ${counter} icons from ${iconSet.info?.name || prefix}`);
}
Functions
Functions used in this code sample:
- getIconData() to extract data for one icon from the icon set.
- iconToSVG() to generate attributes and HTML for SVG.
- iconToHTML() to convert the result of iconToSVG() to string.
Source
For icon set source, this example uses individual icon set package.
If you need to read from a different file, replace that code with something like this:
ts
import { readFileSync } from 'fs';
const icons = JSON.parse(readFileSync('whatever.json', 'utf8'));
Typecast it to IconifyJSON if you are using TypeScript:
ts
import type { IconifyJSON } from '@iconify/types';
import { readFileSync } from 'fs';
const icons = JSON.parse(readFileSync('whatever.json', 'utf8')) as IconifyJSON;
Output
Example outputs SVG to console.
If you need to write it to a file, use file system function, such as writeFileSync() or one of its asynchronous counterparts.
Icon size
In this example all generated icons have height="1em".
You can remove that by adding customisations as second parameter to iconToSVG():
js
const renderData = iconToSVG(iconData, {
// 'unset' removes dimensions from icon
height: 'unset',
});