Chapter 7: Gatsby – An Introduction

Gatsby is the second part of the three-part Jamstack system used in this book. The definition that Gatsby gives for itself is as follows:

"A free and open source framework based on React that helps developers build blazing fast websites and apps."

Since it is a free and open source framework, all of the code is easily examined and modifiable. Secondly, the websites and apps that Gatsby produces are blazing fast because the HTML pages that it creates are actual files, and not just produced through backend processes written in server-side languages.

First, we'll learn what React is, then, we will look at how Gatsby's basic project is structured, examining its file and folder structure.

The main topics that we will cover in this chapter are as follows:

  • Gatsby, built on React
  • Gatsby basic project structure
  • The gatsby develop command

Technical requirements

For this chapter, the Gatsby application needs to be installed, and a Terminal program and a web browser are required.

Gatsby, built on React

React is a JavaScript library used to create user interfaces. It uses declarative syntax and also a modular component-based system. Since Gatsby is built on top of React, you will quickly discover many pieces of React as you learn more about Gatsby. Another part of the Gatsby ecosystem called JSX is also used by Gatsby. JSX allows Gatsby page elements to be written using the familiar HTML tag format and allows the use of attributes to pass parameters to them. Each JSX tag can be a single unit of a project. Since JSX tags are also JavaScript, they may be integrated with JavaScript programming logic.

Since React is one of many JavaScript libraries and frameworks, such as Angular and Vue, the framework itself is quite large, with a healthy ecosystem, and much learning is required to develop proficiency. Luckily, there are many training courses specific to React should you want to more deeply learn how to use it. While learning React is outside of the scope of this book, learning Gatsby will indirectly expose you to some of React's ways of doing things.

Gatsby basic project structure

In this project, the project's files were created through https://create.sanity.io. During the creation process, Gatsby's project file structure and configuration were automatically installed directly in the /web folder, and this is roughly equivalent to what would be installed using Gatsby's new project creation command.

If Gatsby was created using the -g flag, which signifies globally, it gets installed and becomes available system-wide to the user:

npm install –g gatsby

Otherwise, Gatsby commands can be run in the directory where it was installed according to the package.json file.

A new project can be created, alternatively, by typing the following command in the Terminal:

gatsby new projectname

In the preceding example, projectname is the name of your chosen project and will also become the name of the folder created wherever the command is typed.

We'll take a closer look at the file structure of our project in the following sections.

gatsby-config.js

The first file that we will learn about is gatsby-config.js. This file is installed in the /web folder.

Next, we'll look at the three main points of the file:

  • Its structure
  • Its syntax
  • Gatby's Sanity installation

Let's begin.

Structure

The file begins with module.exports, which is a Node.js way of allowing the contents of the curly braces to be exposed and used in (that is, exported to) other parts of the application:

module.exports = {}

The main part of the file is siteMetadata, which holds the application's metadata, such as title and description, and plugins, which is an array of plugins, represented syntactically by square parentheses. An excerpt of the gatsby-config.js file is shown:

module.exports = {

  siteMetadata: {

    title: `Gatsby Default Starter`,

    description: `Kick off your next, great Gatsby project with this default starter...`,

    author: `@gatsbyjs`,

  },

  plugins: [

    `gatsby-plugin-react-helmet`,

    {

      resolve: `gatsby-source-filesystem`,

      options: {

        name: `images`,

        path: `${__dirname}/src/images`,

      },

    },

    ...

  ],

}

Next, we'll look at the syntax of the file.

Syntax

You may not be familiar with the syntax used throughout Gatsby:

path: `${__dirname}/src/images`,

This syntax, called a template literal, is part of ECMAScript 2015, or ES6, the latest JavaScript specification. The backtick character is used here, where previously, single quotation marks would often have been used.

One disadvantage to single quotation marks is that they are not multi-line, so for example, a plus sign is needed to concatenate, or combine sequentially, the two phrases. Here is an example:

var multilineString = 'This is an example of a ' +

' multi-line string that is more than one line long.';

In ES6, the equivalent can be achieved with the following:

let multilineString = `This is an example of a

multi-line string that is more than one line long.`

Additionally, the let keyword is used in place of the var keyword. Whereas previously, only a variable (var) could be declared, now let can be used to assign a value that can change. The constant (const) keyword can be used to designate a value that cannot change, meaning that it is immutable.

Additionally, string interpolation is achieved by enclosing a variable in curly braces (also called curly brackets) and then preceding it with a dollar sign ($). This allows using both variables and simply strings within the same expression as shown:

path: `${__dirname}/src/images`,

Here, the __dirname variable will be replaced with the name of the directory. See the following example:

path: `/home/chris/src/images`

Finally, let's learn how to configure Gatsby to work with Sanity.

Sanity's Gatsby installation

Since the version of Gatsby used in the book was installed and configured based on the instructions at https://www.sanity.io/create, it is preconfigured to work with Sanity, even though Gatsby may obtain and use information from many different types of information sources. This happens through Gatsby's source plugins, which are named in the following format:

gatsby-source-name

The name value in the preceding snippet could be replaced with Sanity (gatsby-source-sanity), WordPress (gatsby-source-wordpress), Drupal (gatsby-source-drupal), or any of hundreds of different types of data sources at the time of writing this book. The default Gatsby source is gatsby-source-filesystem. In Chapter 9, Gatsby Source Plugins, we will discuss this in more detail.

This is an example of the gatsby-source-sanity plugin. It has a list of options:

{

      resolve: "gatsby-source-sanity",

      options: {

        ...clientConfig.sanity,

        token: process.env.SANITY_READ_TOKEN,

        watchMode: !isProd,

        overlayDrafts: !isProd

      }

}

The first thing to notice is the following line:

...clientConfig.sanity,

The triple period is used in JavaScript as the spread operator, which assigns all the object attributes into separate variables. But first, let's examine what happens beforehand.

The first few lines of this configuration file are important:

// Load variables from `.env` as soon as possible

require('dotenv').config({

  path: `.env.${process.env.NODE_ENV || 'development'}`

})

const clientConfig = require('./client-config')

const isProd = process.env.NODE_ENV === 'production'

These lines are important because they determine Gatsby's environment variables and set up the Sanity integration. An environment variable is a variable whose value can vary depending on the environment in which it is used.

For example, in production, an email may be sent after completing a form, whereas in the development environment, it would not be sent.

dotenv

The dotenv file is a convention used to store configuration values. It is usually not committed to source code control, GitHub in this case, so that credentials and passwords may be kept private:

require('dotenv').config({

  path: `.env.${process.env.NODE_ENV || 'development'}`

})

There is an example of this file in the /web directory, namely .env.production, with the following format:

GATSBY_SANITY_PROJECT_ID="abcd1234"

GATSBY_SANITY_DATASET="production"

process.env.NODE_ENV is used to determine which environment is currently being used. development is the default environment used if none is specified, so to enable this file to be used, it must exist in the correct format. Create a copy of .env.production and name it env.development. The .env.production file will be used for production deployments.

Client configuration

The next line requires loading the contents of the client-config file, meaning that it must bring its contents into the current code.

Here are the contents of the file. This is used to set two values, projectId and dataset. It assigns the values from the .env file, if present, or else the actual names provided when the project was created:

module.exports = {

  sanity: {

    projectId: process.env.GATSBY_SANITY_PROJECT_ID || abcd1234',

    dataset: process.env.GATSBY_SANITY_DATASET || 'production'

  }

}

These values get set into the clientConfig variable, and then the contents are spread into the gatsby-source-sanity options where they are used to connect to the Sanity GraphQL API:

options: {

...clientConfig.sanity,

const clientConfig = require('./client-config'),

At this point, the clientConfig constant holds the Sanity configuration.

Next, let's learn about Gatsby's key files.

Key Gatsby files

Three key files in any Gatsby project are gatsby-ssr.js, gatsby-node.js, and gatsby-browser.js. They collectively belong to the Gatsby API. Each file has a particular purpose. Interestingly, each of these files is optional, so they can be created and added to the project as needed.

It's important to learn how the build process works. Remember that since a static site generator literally produces only files, once a web page is produced, it can no longer execute server-side code. All the server-side code execution will occur in a file called gatsby-ssr.js.

Let's look at the three key files in detail.

  • gatsby-ssr.js: SSR is an acronym for server-side rendering, so it soon becomes clear what the purpose of this file is. This file allows you to modify the content of the pages as they are being generated (rendered) on the server by Gatsby. The functions that can be called from inside of this file will interact with the pages at build time as they are rendered.
  • gatsby-node.js: Since Gatsby uses Node.js, the functions in this file allow Gatsby to tap into the entire process.
  • gatsby-browser.js: This is the file where the actual interaction on the page will occur after the web pages are rendered.

Gatsby folders

Here is a list of the main Gatsby folders.

src

This folder contains the Gatsby source files, including images and the cascading style sheets that are used to style the website. Additionally, the following folders are contained within the src folder.

  • Components: In this directory are the building blocks that will be used for website construction. Inside of this directory, there will be pieces of content used across multiple pages.
  • Pages: The contents of this directory are used for single pages; for example, an about us page, where it is the only page of its type. Another example is a 404 page, used when a user enters a web address into the browser address bar that doesn't exist, or clicks a link to a page on the website that doesn't exist either. Each page should have a unique layout. If the pages are too similar, then templates should be used where many of the same types exist, such as for blog articles.
  • Templates: As mentioned previously, a template is used to create many pages of the same type, where all of the pages for a single template have almost the exact same format and layout, for example, with just the page title, headline, and body content differing.

public

Located outside of the src directory, this folder is where the deployed website pages will be created if they do not already exist when gatsby build is run in the command line. This is also where the files will be referenced as the document root when a Gatsby website is first viewed using the gatsby serve command. The contents of the public directory may be deleted and recreated at any time since running gatsby build will always recreate them.

The complete Gatsby documentation may be found at https://www.gatsbyjs.com/docs/, and looks as follows:

Figure 7.1 – Gatsby website documentation

Figure 7.1 – Gatsby website documentation

Now that we've learned about Gatsby's file and folder structure, we will move on to learn how to use Gatsby. To start up Gatsby, we'll need to use the command line. Start Gatsby in development mode.

The gatsby develop command

Using Gatsby at the command line provides many different types of functionality for the various project stages. Initially, the gatsby develop command will start up Gatsby in development mode. This allows changes to be viewed in real time. The command won't stop running until you press Ctrl + C. This key combination is used in the UNIX operating system to terminate (kill) a process.

From inside the /web directory, type gatsby develop, as this will cause the Gatsby development environment (.env.development) to run, using the development configuration, as opposed to the production configuration (.env.production). Also, it will create a GraphQL playground called GraphiQL (pronounced like graphical). This will allow us to actually interact with Sanity's GraphQL interface and to begin to write, test, and view the results of the queries needed to create our events website.

Summary

In this chapter, we learned about what Gatsby is and how it is built using JavaScript and React. Next, we learned how its configuration file is created, and what its main parts are. We also learned how to configure the gatsby-source plugin to interact with Sanity. We also learned about the gatsby develop command and how to start up a project.

In the next chapter, we'll begin our journey with GraphiQL, a GraphQL playground, and move closer to creating a website. This will allow us to design, execute, and test GraphQL queries within the Gatsby context.

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

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