# Lesson 20: Setting up fonts

There’s a real performance benefit to serving fonts locally, especially in terms of latency and cache control, so that’s what we’re going to do in this lesson.

This certainly isn’t a crucial strategy—especially in the context of our website project—but I wanted to show you how useful Gulp is.

In this lesson, we’re going to grab some Google Fonts (opens new window) and pull them down to serve locally.

# Adding a fonts task

The process of this task is going to be:

  1. Grab the CSS that’s served up by Google Fonts.
  2. Grab the font assets that the CSS asks for.
  3. Put those assets in our dist folder.
  4. Generate some CSS and add it to the <head>.

Create a new file in your gulp-tasks folder called fonts.js and add the following to it:

const {dest, src} = require('gulp');
const GetGoogleFonts = require('get-google-fonts');

const fonts = async () => {
  // Setup of the library instance by setting where we want
  // the output to go. CSS is relative to output font directory
  const instance = new GetGoogleFonts({
    outputDir: './dist/fonts',
    cssFile: './fonts.css'
  });

  // Grabs fonts and CSS from google and puts in the dist folder
  const result = await instance.download(
    'https://fonts.googleapis.com/css2?family=Literata:ital,wght@0,400;0,700;1,400&family=Red+Hat+Display:wght@400;900'
  );

  return result;
};

module.exports = fonts;

Remember in lesson 18 where we said that Gulp tasks can just return a Promise? We’re demonstrating that now because this task is a good ol’ asynchronous JavaScript function.

All we’re using is a handy library called get-google-fonts (opens new window) that does exactly what we described above, in the task breakdown.

The two fonts we’re using, Literata (opens new window) and Red Hat Display (opens new window) get pulled down locally, then fonts.css is generated.

The eagle-eyed amongst you will remember that we already added that to our <head> earlier, so now, all we need to do is wire it up to our gulpfile.

Before we do that, though. Let’s install our dependency. Open up your terminal in eleventy-from-scratch and run the following command:

npm install get-google-fonts

# Adding the task to the gulpfile

Open up eleventy-from-scratch/gulpfile.js and on line 4, before the sass task, add the following:

const fonts = require('./gulp-tasks/fonts.js');

Then, in the parallel function on line 16, add fonts to the arguments. It should look like this:

exports.default = parallel(fonts, sass);

If that’s unclear, here’s a diff to compare with:

- exports.default = parallel(sass);
+ exports.default = parallel(fonts, sass);

# Wrapping up

This has been a nice, short lesson to follow the monster that was setting up Sass! That’s because that we’ve already done the hard work with Gulp, so all we’re doing now is filling in the gaps.

Let’s wrap up this module in the next lesson, where we’re going to optimise our images.