Created
September 30, 2021 14:50
-
-
Save joakimriedel/b001b5bedd70274adcb6238b267565d8 to your computer and use it in GitHub Desktop.
Plugin for svgo to set fill to currentColor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}, | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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