The Missing Bit

Using SVG sprites in elm with webpack
June 26, 2017

SVG sprites is the new way to use icons in web app. Actually it is not “that new”, but support now in 2017 is quite good.

It is actually quite easy to use them from elm.

First, you need some webpack magick, install the svg-sprint-loader loader.

Then somewhere inside your javascript app, for example where you require your Main elm file, add this:


var req = require.context("assets/icons", true, /\.svg$/)


var Elm = require('./src/Main.elm')

This code iterates on the .svg files within assets/icons and required them all. You can customize it to your need.

Then, you can use them from elm with something like this:

import Html exposing (Html, text, a, i, div, br)
import Html.Attributes exposing (class, value, href)
import Html exposing (Attribute)
import Json.Decode as Json
import Svg
import Svg.Attributes as SvgAttr
import Style.Icon as Style
import Html.CssHelpers
import Css.Helpers
import Style.Constants as Constants

type Icon
    = BrokenHeart
    | Heart
    | Logo

icon : Icon -> Html msg
icon icon =
        [ SvgAttr.class "icon"
        [ Svg.use [ SvgAttr.xlinkHref ("#" ++ (iconToString icon)) ] []

iconToString : Icon -> String
iconToString icon =
    case icon of
        BrokenHeart ->

        Heart ->

        Logo ->

This code is straightforward, it uses <svg use"#iconname" /> to show the SVG icon. The iconToString function returns the name of the icon (which is the filename required in webpack).