Skip to content

使用 Iconify Utils 导出 SVG

本教程是 Iconify Utils 代码示例 的一部分。

导出 SVG

这是一个使用 Iconify Utils 从图标集生成 SVG 的示例:

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);

异步示例

这是另一个示例,它:

  • 使用异步函数解析图标集。
  • 使用 @iconify/json 作为数据源。
  • 使用现代 JavaScript 编写,而非 TypeScript。
demo.js
jsimport { 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}`);
}

函数

此代码示例中使用的函数:

数据源

对于图标集数据源,本示例使用 独立图标集包

如果你需要从其他文件读取,可以将该代码替换为类似以下内容:

tsimport { readFileSync } from 'fs';

const icons = JSON.parse(readFileSync('whatever.json', 'utf8'));

如果你使用的是 TypeScript,请将其类型转换为 IconifyJSON

tsimport type { IconifyJSON } from '@iconify/types';
import { readFileSync } from 'fs';

const icons = JSON.parse(readFileSync('whatever.json', 'utf8')) as IconifyJSON;

输出

示例将 SVG 输出到控制台。

如果你需要将其写入文件,请使用文件系统函数,例如 writeFileSync() 或其对应的异步函数之一。

图标尺寸

在此示例中,所有生成的图标都具有 height="1em"

你可以通过向 iconToSVG() 添加自定义配置作为第二个参数来移除它:

jsconst renderData = iconToSVG(iconData, {
   // 'unset' 会移除图标的尺寸
   height: 'unset',
});