Files

66 lines
1.5 KiB
JavaScript
Raw Permalink Normal View History

2024-02-01 22:38:21 +09:00
import { optimize } from 'svgo';
2024-01-18 20:36:48 +09:00
import * as prettier from 'prettier';
2024-02-01 22:38:21 +09:00
import { parseSync, stringify } from 'svgson';
2024-07-01 21:28:11 +02:00
import DEFAULT_ATTRS from '../../tools/build-icons/render/default-attrs.json' assert { type: 'json' };
/**
* Optimize SVG with `svgo`.
* @param {string} svg - An SVG string.
2021-03-23 19:26:50 +01:00
* @returns {Promise<string>} An optimized svg
*/
async function optimizeSvg(svg, path) {
const result = optimize(svg, {
path,
plugins: [
{
name: 'preset-default',
params: {
overrides: {
convertShapeToPath: false,
mergePaths: false,
},
},
},
{
name: 'removeAttrs',
params: {
attrs: '(fill|stroke.*)',
2024-02-01 22:38:21 +09:00
},
},
],
});
return result.data;
}
/**
* Set default attibutes on SVG.
* @param {string} svg - An SVG string.
2021-03-23 19:26:50 +01:00
* @returns {string} An SVG string, included with the default attributes.
*/
function setAttrs(svg) {
2021-03-23 19:26:50 +01:00
const contents = parseSync(svg);
2021-03-23 19:26:50 +01:00
contents.attributes = DEFAULT_ATTRS;
2021-03-23 19:26:50 +01:00
return stringify(contents);
}
/**
* Process SVG string.
* @param {string} svg An SVG string.
* @returns {Promise<string>} An optimized svg
*/
function processSvg(svg, path) {
2021-03-23 19:26:50 +01:00
return (
optimizeSvg(svg, path)
2021-03-23 19:26:50 +01:00
.then(setAttrs)
2024-02-01 22:38:21 +09:00
.then((optimizedSvg) => prettier.format(optimizedSvg, { parser: 'babel' }))
2021-03-23 19:26:50 +01:00
// remove semicolon inserted by prettier
// because prettier thinks it's formatting JSX not HTML
.then((svg) => svg.replace(/;/g, ''))
2021-03-23 19:26:50 +01:00
);
}
export default processSvg;