vite-plugin-svg-sprite
Version:
SVG sprite plugin for Vite
96 lines (92 loc) • 3.85 kB
JavaScript
import p from 'node:path';
import fs from 'node:fs';
import crypto from 'node:crypto';
import micromatch from 'micromatch';
import { optimize } from 'svgo';
import { svgToSymbol } from './svg-to-symbol.js';
const { stringify } = JSON;
const exportTypes = ['vanilla', 'react', 'vue'];
function getHash(content) {
const h = crypto.createHash('sha256');
h.update(content);
return h.digest('hex');
}
function prepareTemplate(props) {
return (options) => {
var _a;
return `
import addSymbol from 'vite-plugin-svg-sprite/runtime/inject.js';
${(_a = props.adapterImport) !== null && _a !== void 0 ? _a : ''}
const id = ${stringify(options.id)};
const name = ${stringify(options.name)};
const symbolXml = ${stringify(options.symbolXml)};
const { dispose } = addSymbol(symbolXml, id);
export default ${props.adapter};
export const attributes = ${stringify(options.attributes)}
if (import.meta.hot) {
import.meta.hot.dispose(dispose);
import.meta.hot.accept();
}
`;
};
}
function getModuleTemplate(type = {}) {
if (type.exportType === 'custom') {
if (!type.adapter) {
throw new Error('Export type is set to "custom", but adapter is not provided. Please add "adapter" option in config.');
}
return prepareTemplate({ adapter: type.adapter.toString() });
}
const { exportType = 'vanilla' } = type;
if (!exportTypes.includes(exportType)) {
throw new Error('Unknown export type, supported types: "custom", "react", "vanilla", "vue".');
}
return prepareTemplate({
adapterImport: `import { adapter } from 'vite-plugin-svg-sprite/runtime/adapters/${exportType}.js';`,
adapter: 'adapter(id, name)'
});
}
export default (options) => {
var _a;
const match = (_a = options === null || options === void 0 ? void 0 : options.include) !== null && _a !== void 0 ? _a : '**.svg';
const svgoOptions = options === null || options === void 0 ? void 0 : options.svgo;
const moduleTemplate = getModuleTemplate(options);
const plugin = {
name: 'svg-sprite',
async transform(src, filepath) {
var _a, _b, _c;
if (!micromatch.isMatch(filepath, match, {
dot: true,
})) {
return undefined;
}
const code = await fs.promises.readFile(filepath, 'utf-8');
const hash = getHash(code).slice(0, 8);
const { name } = p.parse(filepath);
const optimizedSvg = optimize(code, {
...svgoOptions,
plugins: [
{
name: 'prefixIds',
params: {
prefix: hash,
},
},
...(_a = svgoOptions === null || svgoOptions === void 0 ? void 0 : svgoOptions.plugins) !== null && _a !== void 0 ? _a : [],
],
}).data;
const symbolId = ((_b = options === null || options === void 0 ? void 0 : options.symbolId) !== null && _b !== void 0 ? _b : 'icon-[name]').replace(/\[hash\]/g, hash).replace(/\[name\]/g, name);
const symbolResults = svgToSymbol(optimizedSvg, symbolId);
if (!symbolResults) {
throw new Error(`invalid svg file: ${filepath}`);
}
const { symbolXml, attributes } = symbolResults;
return {
code: moduleTemplate({ id: symbolId, name, symbolXml, attributes }),
moduleSideEffects: (_c = options === null || options === void 0 ? void 0 : options.moduleSideEffects) !== null && _c !== void 0 ? _c : true,
map: { mappings: '' },
};
},
};
return plugin;
};