Essential Gatsby plugins. Part 3, PWA/Styling and the rest.

Table of contents

This post is part of a series. I believe you can follow without reading the whole thing but I suggest following the links to other parts when something is not clear.

Go back to Part 2

4) PWA

In this section, we’ll see 2 plugins that help us make our application a progressive web app, with almost no effort.

gatsby-plugin-manifest

The first one is gatsby-plugin-manifest. This plugin creates webmanifest files for your application and places them at you public folder. In addition to that, it creates a set of icons with different sizes, from a high-resolution icon you specify (a 512px icon would be perfect). Finally, if you use the basic configuration, it automatically includes a smaller version of that icon in your pages as a favicon. You can install it with:

npm i gatsby-plugin-manifest

and the basic configuration is the following:

gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: "My site name",
        short_name: "SiteName",
        start_url: "/",
        background_color: "#B9E3C6",
        theme_color: "#59C9A5",
        display: "minimal-ui",
        icon: "src/images/logo_512px.png",
      },
    },
  ],
};

The generated icons are placed at public/icons/ folder. Compared to the alternative which is to use an online favicon generator this is much more convenient.

gatsby-plugin-offline

The second plugin is gatsby-plugin-offline. This plugin installs a service worker using Google’s library Workbox. It leverages all the goods a service worker has to offer including file caching, enables the app to run offline after first visit and more.

* One thing to note with gatsby-plugin-offline is that you should declare it AFTER gatsby-plugin-manifest if you want it to also cache the manifest file. You can install it with:

npm i gatsby-plugin-offline

And your gatsby-config.js file should look like:

gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: "Dev Diary",
        short_name: "devdiary",
        start_url: "/",
        background_color: "#B9E3C6",
        theme_color: "#59C9A5",
        display: "minimal-ui",
        icon: "src/images/coding.png",
      },
    },
    `gatsby-plugin-offline`,
  ],
};

You may encounter this issue while using the plugin. If that’s the case you’ll have to upgrade your gatsby version or follow other suggestions in the GitHub issue. You can customize it further but you must be careful with the changes because you may break the functionality of the service worker. In most cases, the default configuration should be fine.

With these two plugins, you make your app a PWA with little effort. If you also have SSL, you can easily score 100 on Lighthouse in the PWA metrics. Let’s continue now by seeing what plugins you can use to style your Gatsby application.

5) Styling

In this section we’ll talk about Typographyjs and styled-components. Additionally, we’ll briefly mention what other options you have for styling. The first one is used more for global styles and the second is used for component styling. We’ll start with the first, which is no other than typographyjs.

gatsby-plugin-typography

Typographyjs is a library developed by the creator of Gatsby Kyle Mathews. It allows you to define global styles for your application, import fonts (including any Google font) and if you wish, you can choose one the predefined themes to style your application. If you don’t feel like styling and you want something ready to go, the available themes can make your day. Check them out and pick one you like.

gatsby-plugin-typography enables us to use the Typographyjs library in Gatsby, efficiently. I should point out here that the official Gatsby tutorial has a really nice guide on using the typography plugin. In order to use Typographyjs in our Gatsby app we’ll need to install 3 dependencies:

npm i gatsby-plugin-typography react-typography typography

After installing the dependencies, you’ll have 2 more things to do. The first is to create a typography.js file, preferably by convention, in the src/util/ folder. If you choose to use the github theme for example this file would look like:

src/utils/typography.js
import Typography from "typography";
import githubTheme from "typography-theme-github";

const typography = new Typography(githubTheme);

// Hot reload typography in development.
if (process.env.NODE_ENV !== "production") {
  typography.injectStyles();
}

export default typography;

Of course, you’ll need to install the github theme also with:

npm i typography-theme-github

In the other hand if you want to create a custom configuration and additionally use some Google Fonts, your typography.js file could look like:

src/utils/typography.js
// In this example, I use the Mali font for headings and the Nunito for the body.
// I also want the body font size to be 20px.
import Typography from "typography";

const typography = new Typography({
  baseFontSize: "20px",
  headerFontFamily: ["Mali", "cursive"],
  bodyFontFamily: ["Nunito", "sans-serif"],
  headerWeight: 700,
  googleFonts: [
    {
      name: "Mali",
      styles: ["700", "400"],
    },
    {
      name: "Nunito",
      styles: ["400"],
    },
  ],
});

// Hot reload typography in development.
if (process.env.NODE_ENV !== "production") {
  typography.injectStyles();
}

export default typography;

* A quick tip: If you want to pair google fonts, some nice online tools are Fontjoy and FontPair.

Now the second thing you have to do is to declare the typography.js file you’ve created, in the gatsby-config.js, along with the gatsby-plugin-typography. This doesn’t come as a surprise, we did that for every plugin so far except gatsby-image if you remember. You can do that by adding the following in your gatsby-config.js:

gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-typography`,
      options: {
        pathToConfigModule: `src/utils/typography`,
      },
    },
  ],
};

The configurations we saw here are considered minimal but they may serve you well. If you wish to do more check the documentation. For example, you can use in your components some helper methods from the typographyjs library. It’s not the best documentation because I find that the information is split between places (Gatsby site, Typographyjs site, GitHub). So be ready for that.

We saw how to add application wide styling, now let’s see how we can style our individual components.

gatsby-plugin-styled-components

Styled components is a really cool and popular library that allows you to write actual CSS inside your JavaScript files. A fancy term you may encounter for that is CSS-in-JS. They achieve that by utilizing tagged template literals. They basically pass parameters to functions by using double “backticks” `. In order to use it in Gatsby we have some installing to do.

npm i gatsby-plugin-styled-components styled-components babel-plugin-styled-components

We also have to define the styled-components plugin in our gatsby-config.js:

gatsby-config.js
module.exports = {
  plugins: [`gatsby-plugin-styled-components`],
};

Now if we want to use it in our index.js page to style a regular h1 heading and the Link component from Gatsby, we could write the following :

src/pages/index.js
import React from "react";
import Link from "gatsby-link";
import styled from "styled-components";

const StyledHeading = styled.h1`
  font-size: 40px;
  font-weight: bold;

  @media screen and (max-width: 576px) {
    font-size: 32px;
  }
`;
const CustomLink = styled(Link)`
  text-decoration: none;
  color: purple;
  transition color .3s ease-out;

  &:hover {
    color: orange;
  }
`;
const IndexPage = () => (
  <div>
    <StyledHeading>Styled components are cool!</StyledHeading>
    <p>
      Check out the{" "}
      <CustomLink to="https://www.styled-components.com/docs">
        documentation.
      </CustomLink>
    </p>
  </div>
);

export default IndexPage;

With styled-components we can also define global styles for our application. We can do that by importing the createGlobalStyle helper method (this method was removed in version 4). We can do it in any component but a nice place for that would be our layout component. So we can write the following inside our layout.js file:

src/components/layout.js
import React from "react";
import styled, { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
  }
  a {
    text-decoration: none;
    color: orangered;
  }
`;

const LayoutContainer = styled.div`
  width: 100%;
  padding: 30px 1rem 50px;
`;
const Layout = ({ children }) => (
  <LayoutContainer>
    <GlobalStyle />
    {children}
  </LayoutContainer>
);
export default Layout;

You can do almost anything in CSS with styled-components and here I show only trivial stuff. So I recommend to check out a gatsby tutorial on styled components and the styled components documentation. Now let’s see some alternatives we have for component styling.

Component styling alternatives

If you want to style your components, styled-components is not your only option. You can use a different CSS-in-JS library like Glamor or you can use CSS modules. Because I don’t use those libraries for styling my components, I won’t give an overview of how to use them, because I’m not familiar with them. If you wish to use those libraries instead, Gatsby has a tutorial for Glamor and in the starter tutorial a section for CSS modules.

And with that, we finish the styling section of the guide. Now let’s see some other useful plugins.

6) Other notable plugins

In this section, we’ll see some popular plugins that don’t necessarily fit in the previous sections or I can’t find a relationship between them. Let’s start with the Google Analytics plugin, which could have arguably been in the SEO section.

gatsby-plugin-google-analytics

The google analytics plugin integrates Google Analytics into your Gatsby site. It’s not hard to add Google Analytics in your site manually without this plugin. For example you can use the gatsby-plugin-react-helmet we saw earlier and add a <script/> tag inside the head of the document. This plugin though, offers out of the box some nice options like the anonymize or the respectDNT options. Like almost any other Gatsby plugin you can configure it further, past the minimal configuration I’ll show you here. You can install it by typing in your command line:

npm i gatsby-plugin-google-analytics

and you declare it in your gatsby-config.js by writing:

gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        trackingId: "YOUR_GOOGLE_ANALYTICS_TRACKING_ID",
        // Puts tracking script in the head instead of the body
        head: false,
        // Setting this parameter is optional
        anonymize: true,
        // Setting this parameter is also optional
        respectDNT: true,
        // Avoids sending pageview hits from custom paths
        exclude: ["/preview/**", "/do-not-track/me/too/"],
      },
    },
  ],
};

If you visit the plugins page in Gatsby site you’ll find more options and related components you can use. We now continue with a simple plugin that has to do with the user experience.

gatsby-plugin-nprogress

gatsby-plugin-nprogress displays a “YouTube/StackOverflow” like progress indicator at the top of your page if the page takes longer than 1 second to load (after clicking an internal link). If you go to NProgress Homepage/playground you can see it in action. Otherwise, if you are a lazy bastard like me, you can watch me doing that for you in the gif below:

nprogress plugin in action.

You can change the color of the indicator to match the style of your site or hide the spinner at the top right. You can install it by typing:

npm i gatsby-plugin-nprogress

and you configure it in your gatsby-config.js:

gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-nprogress`,
      options: {
        color: `darkorange`,
        showSpinner: true,
      },
    },
  ],
};

This is one plugin you hope that’ll never get used in your Gatsby site. To be honest I usually install and so far I haven’t seen it working in my sites. Maybe if you wait for external data in the componentDidMount method it’ll show up. For more configuration options check the NProgress documentation on GitHub. Next plugin and last, is a “sneaky” one.

gatsby-plugin-page-creator

Believe it or not gatsby-plugin-page-creator is the second most used plugin. It’s often overlooked because it’s already included in Gatsby by default. This plugin, as the name suggests, creates pages from React components you specify. By default, Gatsby creates pages from the components you specify in src/pages/ folder. But you can also configure it to do that with other components. First of all, you’ll need to install it with:

npm i gatsby-plugin-page-creator

and configure it in your gatsby-config.js:

gatsby-config.js
module.exports = {
  plugins: [
    // You can have multiple instances of this plugin
    // to create pages from React components in
    // different directories.
    //
    // The following sets up the pattern of having multiple
    // "pages" directories in your project
    {
      resolve: `gatsby-plugin-page-creator`,
      options: {
        path: `${__dirname}/src/otherpages`,
      },
    },
  ],
};

Maybe you can use it in large projects for organizing better the source code.

Final words

First of all thank you for reading this article, I hope you’ve learned something you didn’t know already. If you want to contact me, you can leave me a message. Obviously there are more plugins for you to explore in Gatsby’s site and there is a good chance that I missed some good ones. For example, I didn’t mention gatsby-plugin-netlify despite being popular, because I’m not using it. Some other interesting plugins I didn’t bring up are some source plugins (remember gatsby-source-filesystem?) that integrate with CMS’s. For example gatsby-source-contentful that uses the Contentful CMS or gatsby-source-wordpress that integrates with WordPress API. Maybe I’ll write a post in the future about them.

Other things to read

Popular

Previous/Next