Skip to content
On this page

Exporting Iconify icon set

This tutorial is part of export functions documentation in Iconify Tools.

IconSet instance has export() function that exports icon set in IconifyJSON format.

Then you need to convert it to string using JSON.stringify() and save it to file.

Example

example.ts
tsimport { promises as fs } from 'fs';
import {
   importDirectory,
   cleanupSVG,
   runSVGO,
   parseColors,
   isEmptyColor,
} from '@iconify/tools';

(async () => {
   // Import icons
   const iconSet = await importDirectory('svg/test', {
       prefix: 'test',
   });

   // Validate, clean up, fix palette and optimise
   await iconSet.forEach(async (name, type) => {
       if (type !== 'icon') {
           return;
       }

       const svg = iconSet.toSVG(name);
       if (!svg) {
           // Invalid icon
           iconSet.remove(name);
           return;
       }

       // Clean up and optimise icons
       try {
           // Clean up icon code
           await cleanupSVG(svg);

           // Assume icon is monotone: replace color with currentColor, add if missing
           // If icon is not monotone, remove this code
           await parseColors(svg, {
               defaultColor: 'currentColor',
               callback: (attr, colorStr, color) => {
                   return !color || isEmptyColor(color) ? colorStr : 'currentColor';
               },
           });

           // Optimise
           await runSVGO(svg);
       } catch (err) {
           // Invalid icon
           console.error(`Error parsing ${name}:`, err);
           iconSet.remove(name);
           return;
       }

       // Update icon
       iconSet.fromSVG(name, svg);
   });

   // Export as IconifyJSON
   const exported = JSON.stringify(iconSet.export(), null, '\t') + '\n';

   // Save to file
   await fs.writeFile(`output/${iconSet.prefix}.json`, exported, 'utf8');
})();

Released under the Apache 2.0 License.