Last active
December 12, 2017 19:10
-
-
Save sabine/0bd5015b0b4e7e484da003ba61d46e99 to your computer and use it in GitHub Desktop.
SVG spritesheet builder snippet (using svgstore + SVGO) for use with Elm
This file contains 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
var svgstore = require('svgstore'); | |
var fs = require('fs'); | |
var SVGO = require('svgo'); | |
var svgo = new SVGO({ | |
plugins: [ | |
{removeAttrs: { | |
attrs: ['font-family', 'white-space', 'overflow', 'style'], | |
}}, | |
] | |
}); | |
function optimize(symbolId, contents) { | |
inProgress++; | |
svgo.optimize(contents, function (result) { | |
console.log(result); | |
console.log("SVGO Reduced by: "+ (contents.length - result.data.length)); | |
sprites.add(symbolId, result.data); | |
inProgress--; | |
}); | |
} | |
var camelCased = function camelCased(myString) { | |
return myString.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); }); | |
} | |
var sprites = svgstore(); | |
var ElmType = "type alias Sprites ="; | |
var ElmRecord = "sprites ="; | |
var inProgress = 0; | |
var files = fs.readdirSync('./svgs/'); | |
console.log(files); | |
for (var i=0;i<files.length;i++) { | |
var filename = files[i]; | |
var symbolId = filename.split('.')[0]; | |
var ElmName = camelCased(symbolId); | |
optimize(symbolId, fs.readFileSync('./svgs/'+filename, 'utf8')); | |
if (i === 0) { | |
ElmRecord += "\n { "; | |
ElmType += "\n { "; | |
} else { | |
ElmRecord += "\n , "; | |
ElmType += "\n , "; | |
} | |
ElmRecord += ElmName + " = \"" + symbolId + "\""; | |
ElmType += ElmName + " : String"; | |
} | |
ElmRecord += " }\n\n"; | |
ElmType += " }\n\n"; | |
while (inProgress > 0) {}; | |
var Elmfile = "module SVGSprites exposing (..)\n\n" + ElmType + ElmRecord; | |
fs.writeFileSync('./../elm-threadle/src/static/icons/sprites.svg', sprites); | |
fs.writeFileSync('./../elm-threadle/src/elm/SVGSprites.elm', Elmfile); |
This file contains 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 Svg | |
import Svg.Attributes as SvgA | |
import SVGSprites | |
icon : Types.Taco -> (SVGSprites.Sprites -> String) -> List (Svg.Attribute msg) -> Html msg | |
icon taco name attrs = | |
Svg.svg | |
attrs | |
[ Svg.use [ SvgA.xlinkHref (taco.staticUrl ++ "icons/sprites.svg#" ++ (name SVGSprites.sprites)) ] [] | |
] | |
-- usage | |
-- icon taco .heart [ style [ ( "width", "16px" ), ( "height", "16px" ) ], alt "Love", title "Love" ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment