导出 Iconify 图标集
本教程是 Iconify Tools 中 导出函数文档 的一部分。
IconSet 实例包含 export() 函数,用于将图标集导出为 IconifyJSON 格式。
然后,你需要使用 JSON.stringify() 将其转换为字符串并保存到文件中。
示例
example.ts
ts
import { 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
iconSet.forEach((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
cleanupSVG(svg);
// Assume icon is monotone: replace color with currentColor, add if missing
// If icon is not monotone, remove this code
parseColors(svg, {
defaultColor: 'currentColor',
callback: (attr, colorStr, color) => {
return !color || isEmptyColor(color) ? colorStr : 'currentColor';
},
});
// Optimise
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');
})();