Skip to content

Instantly share code, notes, and snippets.

@joakimriedel
Created September 30, 2021 14:50
Show Gist options
  • Save joakimriedel/b001b5bedd70274adcb6238b267565d8 to your computer and use it in GitHub Desktop.
Save joakimriedel/b001b5bedd70274adcb6238b267565d8 to your computer and use it in GitHub Desktop.
Plugin for svgo to set fill to currentColor
import svgToMiniDataURI from "mini-svg-data-uri";
import type { Plugin } from "rollup";
import fs from "fs";
import { optimize, OptimizeOptions } from "svgo";
type PluginOptions = { noOptimize?: boolean; svgo?: OptimizeOptions };
//TODO: remove this once https://github.com/vitejs/vite/pull/2909 gets merged
export const svgLoader: (options?: PluginOptions) => Plugin = (
options?: PluginOptions
) => {
// these options will always be overridden
const overrideOptions: PluginOptions = {
svgo: {
// set multipass to allow all optimizations
multipass: true,
// setting datauri to undefined will get pure svg
// since we want to encode with mini-svg-data-uri
datauri: undefined,
},
};
options = options ?? overrideOptions;
options.svgo = Object.assign(options.svgo ?? {}, overrideOptions.svgo);
return {
name: "vite-svg-patch-plugin",
transform: function (code, id) {
if (id.endsWith(".svg")) {
const extractedSvg = fs.readFileSync(id, "utf8");
const optimized = options.noOptimize
? extractedSvg
: optimize(extractedSvg, options.svgo).data;
const datauri = svgToMiniDataURI.toSrcset(optimized);
return `export default "${datauri}"`;
}
return code;
},
};
};
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { svgLoader } from "./plugins/svgLoader";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
svgLoader({
svgo: {
plugins: [
{
name: "addCurrentColor",
type: "perItem",
fn: (ast, params, info) => {
// if this is a path without fill attribute
if (ast.name === "path" && !ast.attributes["fill"]) {
// add fill attribute of currentColor so it can be easily overridden with css color
ast.attributes.fill = "currentColor";
}
},
},
],
},
}),
],
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment