Iconify Utils

Iconify Utils is a set of reusable functions for working with icon sets and icon data.

Library is written in TypeScript, is available as ES modules for modern development and CommonJS for older scripts.

Installation

To install library run:

npm install @iconify/utils --save

Examples

This is an example of using Iconify Utils to generate SVG from icon set:

demo.ts
// Import full icon set
import { icons } from '@iconify-json/mdi-light';

// Various functions from Iconify Utils
import { getIconData } from '@iconify/utils/lib/icon-set/get-icon';
import { iconToSVG } from '@iconify/utils/lib/svg/build';
import { defaults } from '@iconify/utils/lib/customisations';
// import { replaceIDs } from '@iconify/utils/lib/svg/id';

// Get ful data for 'mdi-light:home'
const iconData = getIconData(icons, 'home', true);
if (!iconData) {
   throw new Error('Home icon does not exist');
}

// Generate data for rendering SVG
// Second parameter is customisations, in this example using default values
const renderData = iconToSVG(iconData, defaults);

/*

Result of iconToSVG() can be used to either generate HTML code or to use in various components

renderData = {
 attributes: {
   width: '1em',
   height: '1em',
   preserveAspectRatio: 'xMidYMid meet',
   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 attributes for SVG element
const svgAttributes: Record<string, string> = {
   'xmlns': 'http://www.w3.org/2000/svg',
   'xmlns:xlink': 'http://www.w3.org/1999/xlink',
   ...renderData.attributes,
};
if (renderData.inline) {
   svgAttributes.style = 'vertical-align: -0.125em;';
}
const svgAttributesStr = Object.keys(svgAttributes)
   .map(
       (attr) =>
           // No need to check attributes for special characters, such as quotes,
           // they cannot contain anything that needs escaping.
           `${attr}="${svgAttributes[attr as keyof typeof svgAttributes]}"`
   )
   .join(' ');

// Generate SVG
const svg = `<svg ${svgAttributesStr}>${renderData.body}</svg>`;

/*

Many icons have elements with unique IDs, such as masks. IDs are meant to be unique.
If generated icon is embedded in HTML, it cannot have IDs that might be present in
another icon. To solve that, replace IDs in content with randomly generated IDs
using replaceIDs():

const svg = `<svg ${svgAttributesStr}>${replaceIDs(renderData.body)}</svg>`;

Uncomment import for replaceIDs() at start of this example.

*/


// Log SVG
console.log(svg);

This is an example of using Iconify Utils to generate SVG from icon data:

demo.ts
import type { IconifyIcon } from '@iconify/types';
import { fullIcon } from '@iconify/utils/lib/icon';
import { iconToSVG } from '@iconify/utils/lib/svg/build';
import { defaults } from '@iconify/utils/lib/customisations';
// import { replaceIDs } from '@iconify/utils/lib/svg/id';

// Icon data in IconifyIcon format
const data: IconifyIcon = {
   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"/>',
   width: 24,
   height: 24,
};

// Add optional properties to icon data
const iconData = fullIcon(data);

// Generate data for rendering SVG
// Second parameter is customisations, in this example setting dimensions to icon's viewBox
const renderData = iconToSVG(iconData, { ...defaults, height: 'auto' });

/*

Result of iconToSVG() can be used to either generate HTML code or to use in various components

renderData = {
 attributes: {
   width: '24',
   height: '24',
   preserveAspectRatio: 'xMidYMid meet',
   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 attributes for SVG element
const svgAttributes: Record<string, string> = {
   'xmlns': 'http://www.w3.org/2000/svg',
   'xmlns:xlink': 'http://www.w3.org/1999/xlink',
   ...renderData.attributes,
};
if (renderData.inline) {
   svgAttributes.style = 'vertical-align: -0.125em;';
}
const svgAttributesStr = Object.keys(svgAttributes)
   .map(
       (attr) =>
           // No need to check attributes for special characters, such as quotes,
           // they cannot contain anything that needs escaping.
           `${attr}="${svgAttributes[attr as keyof typeof svgAttributes]}"`
   )
   .join(' ');

// Generate SVG
const svg = `<svg ${svgAttributesStr}>${renderData.body}</svg>`;

/*

Many icons have elements with unique IDs, such as masks. IDs are meant to be unique.
If generated icon is embedded in HTML, it cannot have IDs that might be present in
another icon. To solve that, replace IDs in content with randomly generated IDs
using replaceIDs():

const svg = `<svg ${svgAttributesStr}>${replaceIDs(renderData.body)}</svg>`;

Uncomment import for replaceIDs() at start of this example.

*/


// Log SVG
console.log(svg);

Functions

Icon sets are stored in IconifyJSON format. Functions for working with icon sets:

Functions for working with IconifyIcon format that represents one icon:

When rendering icon, customisations can be applied to it. For example, changing dimensions, rotating or flipping icon. They are represented by IconCustomisations type. Functions for working with customisations:

Functions for rendering icon:

  • iconToSVG(icon, customisations) generates data needed to render SVG. It does not generate full SVG, only content and list of attributes to add to SVG element, making it easy to use in custom components.
  • calculateSize(size, ratio) calculates icon dimensions. It is used when building icons using iconToSVG().
  • replaceIDs(content) replaces IDs in SVG with unique IDs. IDs used in elements like masks and they must be unique, so multiple icons displayed on the same page using same IDs will result in chaos. This function prevents that chaos.

Functions for working with icon names:

There are also reusable functions for working with colors. They do not really belong to this package, however, they are used by few projects and making a separate package just for colors did not make much sense, so these functions were moved to Iconify Utils package:

  • stringToColor(value) converts string to Color object, returns null on error. This can be used to validate user input. It supports color keywords, hexadecimal colors, RGB, HSL, LAB and LCH colors. Variables are not supported because this is meant for parsing SVGs, which should not reference any external variables.
  • compareColors(color1, color2) compares colors. It also converts RGB to HSL if needed.
  • colorToString(color) converts Color object to string. Combined with stringToColor(), this can be used to validate and clean up user input.