Skip to content

Serving fonts locally

Valentin Degenne edited this page Jan 17, 2024 · 14 revisions

For this strategy we will need to download the fonts and transform the html during build time. In this example we use @web/rollup-plugin-html, however you can use any html transformation logic you want:

rollup.config.js:

import {mdIcon, replaceSymbolsLink} from 'rollup-plugin-md-icon';
import {rollupPluginHTML as html} from '@web/rollup-plugin-html';

const DEV = process.env.NODE_ENV == 'DEV';

export default {
  plugins: [
    DEV
      ? html()
      : [
          mdIcon({ symbols: {} }),
          html({
            transformHtml: (html) =>
              replaceSymbolsLink(
                html,
                '<link rel="stylesheet" href="/material-symbols.css">',
              ),
          }),
        ],
  ],
};

Setting symbols to an empty object is enough to instruct the plugin to download the fonts locally.
Using DEV environment variable in this configuration allows us to use an all-in-one symbols stylesheet during development. We only download and transform html during actual build time.

Downloading fonts during development

If you don't mind downloading the fonts every time you add or remove icons in your sources, then the above configuration can be simplified to:

import {mdIcon} from 'rollup-plugin-md-icon';

export default {
  plugins: [
    mdIcon({
      symbols: {}
    })
  ],
};

and change the link in your index.html:

<head>
  <link rel="stylesheet" href="/material-symbols.css">
</head>

However this is not recommended for two reasons:

  • This can send too much requests over the network.
  • The browser will not always update the cached font, which means you'll have to manually hard reload the page to see the new icons.

symbols: {}

By default files are downloaded under dist directory:

  • dist/material-symbols.css: The stylesheet to include in your page to load the font.
  • dist/material-symbols.woff2: The font containing the set of icons your app needs.

You can customize the paths respectively, e.g.:

mdIcon({
  symbols: {
    stylesheetPath: 'assets/symbols.css',
    fontPath: 'assets/symbols.woff2'
  }
})
Clone this wiki locally