HOWTO: Adding Material Design Icons to tailwind in a Phoenix project

Hello!

Hero Icons are nice, but sometimes you might need an icon set with a larger set.
Material Design Icons are visually quite compatible (imo).

To add them efficiently to your Phoenix project without loading the whole icon font:

Add to mix.exs:

      {:materialdesignicons,
       github: "Templarian/MaterialDesign", sparse: "svg", app: false, compile: false, depth: 1},

Add to tailwindconfig.js

 // Embeds Material Desing Icons into your main.css bundle
    // See your `CoreComponents.icon/1` for more information.
    plugin(function ({ matchComponents, theme }) {
      let iconsDir = path.join(__dirname, "../deps/materialdesignicons/svg");
      let values = {};

      fs.readdirSync(iconsDir).forEach((file) => {
        let name = path.basename(file, ".svg");
        values[name] = { name, fullPath: path.join(iconsDir, file) };
      });

      matchComponents(
        {
          mdi: ({ name, fullPath }) => {
            let content = fs
              .readFileSync(fullPath)
              .toString()
              .replace(/\r?\n|\r/g, "");
            let size = theme("spacing.6");
            return {
              [`--mdi-${name}`]: `url('data:image/svg+xml;utf8,${content}')`,
              "-webkit-mask": `var(--mdi-${name})`,
              mask: `var(--mdi-${name})`,
              "mask-repeat": "no-repeat",
              "background-color": "currentColor",
              "vertical-align": "middle",
              display: "inline-block",
              width: size,
              height: size,
            };
          },
        },
        { values }
      );
    }),

That’s it! Use them with the classes mdi-ICONAME

2 Likes