Chapter 9: Gatsby Source Plugins

In this chapter, we are going to explain how to extend the functionalities of Gatsby by using plugins. We will start by exploring the basics of a plugin, and then look at how to install and maintain a plugin. We will explore where to find a plugin and how Gatsby manages its plugins. At the end of the chapter, we will install and configure two new plugins to our Gatsby application.

We will cover the following topics in this chapter:

  • Understanding plugins
  • Searching, installing, and configuring plugins

Technical Requirements

We will need the following to understand this chapter thoroughly:

  • A Terminal application
  • npm
  • The Gatsby application installed.

The code files for this chapter can be found at https://github.com/PacktPublishing/Jumpstart-Jamstack-Development/tree/chapter_nine.

Note:

The Drupal section is relevant only if you have a Drupal website. GitHub link: https://github.com/PacktPublishing/Jumpstart-Jamstack-Development/tree/chapter_nine_drupal.

The Drupal application with the following modules enabled:

  • RESTful Web Services
  • JSON:API
  • Serialization

Understanding plugins

In this section, we will explore the basics of a plugin, what a plugin is, and why it is needed in a project. We will explore the public collection of open source code, npm. We will explain how semantic versioning control works and why it is important. We will then see how to install and maintain plugins.

Gatsby plugins are Node.js packages, a set of JavaScript and HyperText Markup Language/Cascading Style Sheets (HTML/CSS) files that extend the Gatsby application programming interfaces (APIs) and add new functionalities to the application. You can enable a feature by installing a plugin, and you can disable it by uninstalling the plugin.

The extensible nature of Gatsby allows you to create your plugins in a way that allows you to organize your customized business logic into reusable packages, discussed in the next section.

Node Package Manager

A developer can download plugins from npm, which is a public collection of open source code for JavaScript frameworks such as GatsbyJS. Developers can upload their plugins and let other developers reuse the same code. Other developers can also contribute back to the plugin they have used by fixing bugs or adding functionalities. You can also upload private packages to npm.

You can search for a plugin on npm from the search tool on the following website:

https://www.npmjs.com

On the package page on the aforementioned website, you can find the description of a package, with installation instructions, dependencies, and versions. In the next section, we will explore the package versioning method that uses semantic versioning.

Semantic versioning

In software development, developers assign a unique version number to a unique state of the software. Versioning a software helps developers to choose the right version needed to implement their software. This applies to packages, too.

When a package is created and added to npm, the first recommended version is 1.0.0. With further implementation and bug fixing, the version number increments depending on the type of change introduced.

The packages must follow major.minor.patch semantic versioning, detailed as follows:

  • The major version increments by one when a developer introduces incompatible API changes. The version changes from 1.0.0 to 2.0.0.
  • The minor version increments by one when a developer introduces a backward-compatible new functionality. The version changes from 1.0.0 to 1.1.0.
  • The patch version increments by one when a developer introduces a backward-compatible bug fix. The version changes from 1.0.0 to 1.0.1.

Next, we will see how to install a package from npm.

Installing a package from npm

To install a package from npm, from your Terminal, run the following command:

npm i <package_name>

Here, <package_name> is the name of the package. For example, if you would like to install a package from npm called birdie-hop, you can run the following command on your Terminal:

npm i birdie-hop

With the preceding command, npm will get the latest stable release of the birdie-hop package into your application.

We can also specify the version we want by adding the version to the package name, as shown in the following command:

npm i <[email protected]>

You may have noticed that I have added @version to the package name. For example, if you want to install version 6.1.46 of the birdie-hop package, you can run the following command on your Terminal:

npm i [email protected]

Every time we add a new package, our application keeps track of it inside a package.json file. The new package is listed as a dependency.

Let's explore the package.json file in the next section.

The package.json file

One of the functionalities of the package.json file is to list all the dependencies of a package. It adds the dependencies under the dependencies section when you install a new package.

As you can see in the following example, the package name has been added to the package.json file, along with the version downloaded:

...  

"dependencies": {

    ...

    "birdie-hop": "^1.2.3",

    ...

  }

...

You may have noticed the character before the version number—caret (^), in our case—which tells npm which version to download when we want to install or update the package.

There are two other characters to define version updates: * and ~.

Let's see the difference between these characters. Have a look at the following code snippet:

npm i [email protected]

Adding the version with no character before the version will download that exact version if you have never installed the plugin in your app, or it will update the package to that very same version. Now, have a look at this code snippet:

npm i [email protected]~1.2.3

The tilde (~) tells npm that it can install or update the package to the latest patch release available. In this case, the version will be >1.2.3 and <1.3.0. Next, have a look at the following code snippet:

npm i [email protected]^1.2.3

The caret (^) tells npm that it can install or update the package to the latest minor release available. In this case, the version will be >1.2.3 and <2.0.0. Now, have a look at this code snippet:

npm i [email protected]*1.2.3

The asterix (*) tells npm that it can install or update the package to any major version available. In this case, the version will be >1.2.3 and there is no limit on updates. Let's move on to understanding how to update a plugin.

By default, the packages are going under the dependencies array and will be required by your application in production. You can also set up packages that are only needed in your local development environment or on your testing environment, such as automated testing packages. This package will go under the devDependencies array in the packages.json file and can be added by adding the –save-dev flag, as follows:

npm i birdie-hop –save-dev

Updating a plugin

When a plugin releases an update, we can update our plugin via npm. To update all packages listed in the package.json file, run the following command:

npm update

To update a single package, run the following command:

npm update <package_name>

Here, <package_name> is the name of the package you want to update. If you want to update the birdie-hop package, you can run the following command:

npm update birdie-hop

During updating or installation, npm will check the package.json file and download or update a plugin to the allowed version.

The package.lock file

When you are working in a team, you want all the developers in your team to use the same package versions. In this situation, the package.lock file comes in handy. It is automatically generated when you modify the package.json file or the node_modules folder. It lists all the exact versions of the packages the application should use. The package.lock file will avoid a situation where two developers in the same team working on the same project use two different versions of the birdie-hop package.

In this section, we have explored the main components of a package. We learned where to find the packages and how to install them. We learned about package versioning and how to install and update a specific package to a specific version. We have also explored how package.json and package.lock files play an important role in making sure your application gets the right package with the right version.

In the next section, we will install a package in our Gatsby application.

Searching, installing, and configuring plugins

In this section, we will explore the Gatsby public plugin repository. We will look at how to install a Gatsby plugin and where to find the configuration for the plugins you would like to install.

We will install and configure the gatsby-source-filesystem and gatsby-source-drupal plugins and see how we can use them.

The Gatsby Plugin Library

Gatsby also provides a plugin library, a collection of npm packages tagged with the Gatsby keyword. In this library, it is possible to find standard plugins that will be used on most sites, related to Search Engine Optimization (SEO), Really Simple Syndication (RSS), social media buttons, third-party comment services, e-commerce integration, and more.

Important note

Before you start writing your custom plugin, please make sure it does not already exist in the Gatsby Plugin Library.

There are multiple benefits to using a plugin from the Gatsby Plugin Library. Some of them are listed here:

  • Time-saving: If a plugin fully accomplishes your task, you can install it, configure it, and start using it. If a plugin partially accomplishes your task, you can extend it by adding your custom functionality on top of it.
  • Bug fixing: You or other developers may fix bugs and publish the information on npm, and get these fixes by updating the plugin in your application.
  • Improvement: Same as bug fixing—you or other developers may add new functionality to the plugin and publish it on npm.
  • Security: You or other developers may find security issues with the code or dependencies in a plugin; update the plugin with the latest security release and publish it on npm.

To find a Gatsby plugin, visit the Gatsby Plugin Library at https://www.gatsbyjs.org/plugins/.

The following page provides a Search Gatsby Library textbox that lets you navigate through more than 2,000 plugins! The textbox is on the top left-hand side of the page, as illustrated in the following screenshot:

Figure 9.1 – The Gatsby Plugin Library page

Figure 9.1 – The Gatsby Plugin Library page

Each Gatsby plugin comes with detailed instructions on how to install, configure, and use it. The Gatsby Source plugins allow Gatsby to get the content from a source such as a database, file, RESTful API (where REST stands for REpresentational State Transfer), and so on.

The Starter project that we installed in Chapter 2, Introduction to Sanity comes with the gatsby-source-sanity plugin already installed and configured. Throughout the gatsby-source-sanity plugin, we are able to get content from our Sanity application.

In the following section, we are going to explain how to search for a plugin in the Gatsby Plugin Library. As an example, we are going to install and configure two source plugins: the gatsby-source-filesystem and gatsby-source-drupal plugins.

Searching for a plugin

All Gatsby plugins can be found in the Gatsby Plugin Library at https://www.gatsbyjs.org/plugins/.

On the left-hand side of the page, there is a search tool for a plugin. Start typing the name of a potential keyword for the plugin you are looking for.

For example, if you are looking for the Google Analytics plugin, you can type google analytics.

In our example, we will look for the gatsby-source-filesystem plugin, so we can type source filesystem, as shown in the following screenshot:

Figure 9.2 – The Gatsby Plugin Library page

Figure 9.2 – The Gatsby Plugin Library page

On the left-hand side of the page, it will return all the results containing that keyword. Each result contains the name of the plugin, a description, the number of downloads, and type of plugin. When you click on the plugin result, you will be able to see a description of the plugin and instructions on how to install it.

In the main section of the page, we can now see the name of the plugin, a link to the GitHub page, the type of plugin, a link to the Starter kits using this plugin, a description of the plugin, and instructions on how it install it, as illustrated in the following screenshot:

Figure 9.3 – The gatsby-source-filesystem plugin page

Figure 9.3 – The gatsby-source-filesystem plugin page

Tip

When choosing a plugin, click on View Plugin on GitHub and check how often it is updated, and check the bugs list under the Issue tab to see if there is any conflict with your code base. If you want to try the plugin before you install it in your application, you can install a Starter kit that uses that plugin by clicking on See starters using this. It will then show a list of Gatsby starters that use that plugin.

Now that we have found the plugin on the Gatsby Plugin Library, let's install it on our application.

Installing and configuring the gatsby-source-filesystem plugin

This plugin gets data into your application from your local or remote filesystem. We will use local Markdown files for this example.

Installing the plugin

Plugins are installed through npm via the command line. When you have found the plugin you are looking for, see the installation command on the plugin page, under the Install section, as illustrated in the following screenshot:

Figure 9.4 – The gatsby-source-filesystem plugin page Install section

Figure 9.4 – The gatsby-source-filesystem plugin page Install section

Type the command shown in the preceding screenshot in your Terminal inside the web folder of your project, and press Enter.

This command will download the plugin and its dependencies inside the node_modules folder and add the gatsby-source-filesystem plugin and version to download in the package.json file, under the Dependencies section.

Configuring the plugin

Now, the plugin files are in their own application, but in order to enable a plugin, we need to add it to the gatsby-config.js file located in the root folder of the Gatsby project—in our case, inside the web folder.

The gatsby-config.js file is one of the most important files of the application. It contains configuration for the following:

  • siteMetadata (object)
  • plugins (array)
  • pathPrefix (string)
  • polyfill (Boolean)
  • mapping (object)
  • proxy (object)
  • developMiddleware (function)

To enable a plugin, simply add the plugin name in the plugins array in the gatsby-config.js file, like this:

module.exports = {

  plugins: [

    ...

    'gatsby-plugin-name',

    ...

  ]

}

Some other plugins may also take configuration options that can be added in the plugins array in the gatsby-config.js file, as illustrated in the following code snippet:

module.exports = {

  plugins: [

    ...

    {

      resolve: 'plugin-name',

      options: {

        // Options list, if any

      },

    },

    ...

  ]

}

Now that we know how to enable a plugin, let's enable the gatsby-source-filesystem plugin and tell Gatsby where to find our content. On the Gatsby Plugin page, under the How to use section, there are detailed instructions on how to configure the plugin in your application.

The gatsby-source-filesystem plugin can take three options, as follows:

  • name: The name used by GraphQL queries (required)
  • path: The folder where the actual files live (required)
  • ignore: A list of file extensions to be ignored (optional)

In our case, we can add the configuration in this way:

module.exports = {

  plugins: [

    ...

    {

      resolve: 'gatsby-source-filesystem',

      options: {

        path: '${__dirname}/src/data',

        name: 'md-files',

        ignore: ['**/.*'],

      },

    },

    ...

  ]

}

With the preceding code, we enabled the gatsby-source-filesystem plugin, and we tell Gatsby where to find the files, the name of our content, and to ignore all files starting with a dot. Now, restart your application. From the command line, press Ctrl + C and then run the following command:

npm run dev

As an example, we are going to query data from a Markdown file. We will create a folder called data under our web/src application folder. Inside the data folder, we create all the Markdown files we need. The files are organized in subfolders, and the system will automatically find them. To do that, we need the gatsby-transformer-remark plugin, which we are going to install in the next section.

Installing and configuring the gatsby-transformer-remark plugin

This plugin parses and compiles the Markdown file and converts it to HTML. It also supports frontmatter so that you can define fields such as title, slug, date, image, excerpt, and so on.

Let's install and configure the plugin.

Installing the plugin

As this is a Gatsby plugin it can be found in the plugin library, along with installation and configuration instructions.

Inside your Gatsby folder, run the following command to install the plugin:

npm install --save gatsby-transformer-remark

Configuring the plugin

Once the plugin has been downloaded, we are able to enable it by adding only the plugin name in the gatsby-config.js file, as shown in the following code block:

module.exports = {

  plugins: [

    ...

    'gatsby-transformer-remark',

    ...

  ]

}

That's it! Now, restart your application, and we are ready to create our first content!

Creating the content file

In this section, we are going to create our content inside a Markdown file. As we said, gatsby-transformer-remark lets you add fields into the Markdown file. Let's start adding the frontmatter, as follows:

  1. Create a file inside web/src/data called hello-world.md. At the top and the end of the file, add three dashes. Between those two lines, you can define your frontmatter, as follows:

    ---

    // Define your frontmatter.

    ---

  2. The fields in the frontmatter can be defined as a key/value pair. We can add the information we want. In this case, we will add title, date, and excerpt in the following way:

    ---

    title: Hello World

    date: "2020-07-12T09:01:00"

    excerpt: Hi! This is my first content from a markdown file! I will fill with James Joyce's poem.

    ---

  3. Now that we have the fields, let's add the body and save the file, like this:

    ---

    title: Hello World

    date: "2020-07-20T09:01:00"

    excerpt: Hi! This is my first content from a markdown file! I will fill with a James Joyce's poem.

    ---

    # Lean out of the window

    > Lean out of the window,

    > Goldenhair,

    > I hear you singing

    > A merry air.

    > ...

    > Singing and singing

    > A merry air,

    > Lean out of the window,

    > Goldenhair.

Our file is now ready to be queried by GraphiQL!

Querying the filesystem with GraphiQL

Now that we have all the plugins, configuration, and content file in the right place, let's start querying the content from our GraphiQL.

Go to http://localhost:8000/___graphql and run the following query:

query MyQuery {

  allMarkdownRemark {

    edges {

      node {

        frontmatter {

          title

          date

          excerpt

        }

        html

      }

    }

  }

}

The preceding query will tell GraphQL to retrieve the following fields from the frontmatter section:

  • title
  • date
  • excerpt
  • html

This query will return the following result:

{

  "data": {

    "allMarkdownRemark": {

      "edges": [

        {

          "node": {

            "frontmatter": {

              "title": "Hello World",

              "date": "2020-07-20T09:01:00",

              "excerpt": "Hi! This is my first content from a markdown file! I will fill with a James Joyce poem."

            },

            "html": "<h1>Lean out of the window</h1> <blockquote> <p>Lean out of the window, Goldenhair, I hear you singing A merry air. ... Singing and singing A merry air, Lean out of the window, Goldenhair.</p> </blockquote>"

          }

        }

      ]

    }

  }

}

As you can see, the frontmatter fields are grouped under the frontmatter key, and the rest of the file will be shown as HTML, formatted under the html key.

In this section, we have seen how to search, install, and configure Gatsby plugins. As an example, we have used the gatsby-file-system and gatsby-transformer-remark plugins, we have created a Markdown file, and we have used GraphQL to query our file.

In the next section, we are going to explore how to query another application that uses web services. As an example, we are going to query a Drupal application.

Installing and configuring the gatsby-source-drupal plugin

In this section, we are going to install and configure the gatsby-source-drupal plugin. This plugin lets us get content from a Drupal application. Let's first install this plugin.

Installing a gatsby-source-drupal plugin

As with the gatsby-source-filesystem and gatsby-transform-remark plugins, the gatsby-source-drupal plugin can also be found on the Gatsby plugin search page, along with installation and configuration instructions.

To install the latest stable version of the plugin, run the following command from the command line in your Terminal:

npm install --save gatsby-source-drupal

As usual, the preceding command will download the package into our nodes_modules folder.

Configuring the gatsby-source-drupal plugin

Once the module has been installed, as with the previous plugin, we have enabled it, and we need to add the new plugin inside the plugins array in the gatsby-config.js file.

In this example, we go ahead with the basic configuration, as follows:

module.exports = {

  plugins: [

    ...

    {

      resolve: 'gatsby-source-drupal',

      options: {

        baseUrl: 'site-url', //for example https://example.com

      },

    },

    ...

  ],

}

With the preceding code, we told Gatsby to enable the gatsby-source-drupal plugin and we have specified the Uniform Resource Locator (URL) of the Drupal application.

Now that we have installed and configured the plugin, we can start querying our Drupal application through GraphQL.

Querying Drupal with GraphQL

Once the plugin has been configured, we can test it by querying the Drupal application through GraphiQL.

Go to http://localhost:8000/___graphql and run the following query:

query MyQuery {

  allNodeArticle {

    edges {

      node {

        title

        body {

          value

        }

      }

    }

  }

}

This query will return the following result:

{

  "data": {

    "allNodeArticle": {

      "edges": [

        {

          "node": {

            "title": "Hello world",

            "body": {

              "value": "<p>Lean out of the window,<br /> Goldenhair,<br /> I hear you singing<br /> A merry air.</p> <p>My book was closed,<br /> I read no more,<br /> Watching the fire dance<br /> On the floor.</p> <p>I have left my book,<br /> I have left my room,<br /> For I heard you singing<br /> Through the gloom.</p> <p>Singing and singing<br /> A merry air,<br /> Lean out of the window,<br /> Goldenhair.</p> "

            }

          }

        }

      ]

    }

  }

}

In this section, we have installed and configured the gatsby-source-drupal plugin. We have also queried a Drupal application and have retrieved data from the application.

In the next section, we are going to see how we can query both gatsby-source-filesystem and gatsby-source-drupal plugins within one query.

Querying both filesystem and Drupal plugins together

It is possible to query two content sources within the same query, which is advantageous when building a listing page with content coming from different sources.

Our query will contain calls and fields belonging to both plugins. We will get one single response, containing results from both sources separated by their root name. In this case, the Drupal content will be contained under the allNodeArticle array, and the filesystem content will be contained under the AllMarkDownRemark array.

As we already seen, we can go to http://localhost:8000/___graphql and run the following query:

query MyQuery {

  allNodeArticle {

    edges {

      node {

        title

        body {

          value

        }

      }

    }

  }

  allMarkdownRemark {

    edges {

      node {

        frontmatter {

          title

          date

          excerpt

        }

        html

      }

    }

  }

}

This query will return the following result:

{

  "data": {

    "allNodeArticle": {

      "edges": [

        {

          "node": {...}

        }

      ]

    },

    "allMarkdownRemark": {

      "edges": [

        {

          "node": {...}

        }

      ]

    }

  }

}

As we can see, we have both the Drupal and filesystem content from the two different sources, in the same query result.

Summary

In this chapter, we learned how to extend Gatsby using plugins to enrich the functionality of the application. We learned about the following: what a plugin is; npm; how to use semantic versioning; and how to install and update a plugin. We also learned about the structure of the Gatsby Plugin Library and how to install and configure a Gatsby plugin. We installed and configured the gatsby-source-filesystem and gatsby-transform-remark plugins, and we used GraphQL to query content from a Markdown file. We also installed and configured the gatsby-source-drupal plugin and used GraphQL to query content from a Drupal application.

These plugins are useful when we need to get content from other sources, especially if we need to build an application that aggregates content from different sources.

In the next chapter, we are going to talk about Gatsby components and how pages, templates, and partials are structured, and how they differ.

Further reading

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset