Add Google Fonts in a tailwindcss Plugin

Or from Any Other Fonts CDN.

Mar 12, 2021 · 1 min read

One of the benefits of creating your own tailwindcss plugin is that you can add your own css to any of the different layers (base, components, utilities).

In this case, I wanted to provide a plugin for my fonts of choice. The key for that plugin was to add the imports or font-face definitions right into the base layer.

There are basically two ways of doing it. The tedious one, copying the font-face definitions and modify it to apply it as a json config. Something like:


const plugin = require('tailwindcss/plugin')

module.exports = plugin(function ({ addBase }) {
 addBase({
   '@font-face': [{
       fontFamily: 'Bitter',
       fontStyle: 'italic',
       fontWeight: 400,
       fontDisplay: 'swap',
       src: `url(https://fonts.gstatic.com/s/bitter/v17/raxjHiqOu8IVPmn7epZnDMyKBvHf5D6c4Pz-UnB0n-ChBltdqi4.woff) format('woff')`,
      unicodeRange: 'U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F',
    },
   // ... keep going ...
   }]
 })
})

But this is not good. There should be another way.

Good news, there is another way. Yeah, I spoiled that already.

I did a few more research (in fact it took me a whole morning to figure it out). You can use the @import directive making it easier to maintain, update, etc:


const plugin = require('tailwindcss/plugin')

module.exports = plugin(function ({ addBase }) {
 addBase({
   [`@import url('https://fonts.googleapis.com/css2?family=Bitter:ital,wght@0,300;0,400;0,600;0,700;1,400&display=swap')`]: true
  })
})

As ugly as it looks it works pretty well. The trick here is to define the import statement as a key of the object configuration and set it to true. In this way we can copy and paste the import statement generated by Google Fonts (or any other fonts CDN)

Any viewpoints and opinions expressed in this article are my own and do not, in any way, reflect those of my employer, my colleagues, or anyone else. I speak only for myself, not for them.