Elevating React Web Development with Gatsby - Samuel Larsen-Disney - E-Book

Elevating React Web Development with Gatsby E-Book

Samuel Larsen-Disney

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Gatsby is a powerful React static site generator that enables you to create lightning-fast web experiences. With the latest version of Gatsby, you can combine your static content with server-side rendered and deferred static content to create a fully rounded application. Elevating React Web Development with Gatsby provides a comprehensive introduction for anyone new to GatsbyJS and will help you get up to speed in no time.
Complete with hands-on tutorials and projects, this easy-to-follow guide starts by teaching you the core concepts of GatsbyJS. You'll then discover how to build performant, accessible, and scalable websites with the GatsbyJS framework. Once you've worked through the practical projects in the book, you'll be able to build anything from a personal website to large-scale applications with authentication and make your site rise through those SEO rankings.
By the end of this Gatsby development book, you'll be well-versed in every aspect of the tool's performance and accessibility and have learned how to build client websites that your users will love.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 300

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Elevating

React Web Development

with Gatsby

Practical guide to building performant, accessible, and interactive web apps with React and Gatsby.js 4

Samuel Larsen-Disney

BIRMINGHAM—MUMBAI

Elevating React Web Development with Gatsby

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Ashitosh Gupta

Senior Editor: Hayden Edwards

Content Development Editor: Rashi Dubey

Technical Editor: Joseph Aloocaran

Copy Editor: Safis Editing

Project Coordinator: Rashika Ba

Proofreader: Safis Editing

Indexer: Hemangini Bari

Production Designer: Roshan Kawale

Marketing Coordinator: Anamika Singh

First published: January 2022

Production reference: 1190122

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80020-909-1

www.packt.com

To Carlota, for making me believe I could do this, motivating me when it was tough, and always filling my days with happiness. To my family, for their love and support, and buying this book even though they aren't web developers.

– Samuel Larsen-Disney

Contributors

About the author

Sam studied computer science at King's College, London. He helped design and build American Express' websites. He then moved to BehaviourLab where he led frontend development, before deciding he wanted to get out of finance. He has since become a senior frontend engineer at Zone. He is most at home coding in React, JavaScript, GraphQL, and Gatsby but is always open to learning something new. When coding, he likes to ensure his code is accessible and performant. In the last year, Sam has contributed 1,300+ times to open source projects. He enjoys teaching the next generation to code through his articles and presentations, and at hackathons.

My passion for web development is the direct result of some awesome engineers who took the time to teach me their craft. I would particularly like to thank Adam Wilkinson and Diego Abizaid who challenged what I thought was possible in the browser. I would also like to thank Yannis Panagis, Ryan Gregory, Çelik Köseoğlu, Meghan Avery, Arthur Ceccotti, Ruben Casas, and Joshua Gabrel, who all made my web development journey unique.

About the reviewer

Benjamin Read has been developing websites for the past decade. That covers a lot of ground: from the advent of the iPhone and responsive design to today's isomorphic, serverless, and reactive web applications. A few years ago, he came across an exciting new project called Gatsby. Gatsby catapulted his interests in static sites, GraphQL, content management systems, and other concepts that continue to propel his technical interests today. When he's not working, contributing to open source, or tinkering with new technology, Ben is usually found spending time with his wife and three children, or reading a good book.

Table of Contents

Elevating React Web Development with Gatsby

Contributors

About the author

About the reviewer

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Part 1: Getting Started

Chapter 1: An Overview of Gatsby.js for the Uninitiated

Technical requirements

A brief history of the static web

What is Gatsby?

Community

Sourcing content from anywhere

Building tooling you already know

Supercharging web performance

Gatsby use cases

Documentation sites

Online courses

SaaS products

Design agencies and photo-heavy sites

Gatsby's competitors

Setting up a project

Node.js version 14.15.0+

Gatsby command-line interface

Directory and package setup

Framework files and folders

Creating your first few pages

Summary

Chapter 2: Styling Choices and Creating Reusable Layouts

Technical requirements

Styling in Gatsby

Vanilla CSS

Sass

Tailwind (utility-first CSS framework)

CSS in JS

Picking a styling tool

Styling with CSS

Creating a wrapper component

Using gatsby-browser.js

Verifying our implementation

Styling with Sass

Styling with Tailwind.css

Styling with styled-components

Creating a reusable layout

Site header

Site footer

Layout component

Organization with atomic design

Summary

Chapter 3: Sourcing and Querying Data (from Anywhere!)

Technical requirements

Data in Gatsby

Introducing GraphQL

GraphQL for Gatsby

Using GraphiQL

Using constructed GraphQL queries

Sourcing data from local files

Site metadata

Markdown

MDX

Sourcing data from a Headless CMS

GraphCMS

Prismic

Summary

Chapter 4: Creating Reusable Templates

Technical requirements

Creating templates and programmatic page generation

Blog post template

Blog preview template

Tag page template

Search functionality

Summary

Chapter 5: Working with Images

Technical requirements

Images on the web

Images in Gatsby

The StaticImage component

The GatsbyImage component

Overriding the gatsby-plugin-image defaults

Sourcing images from CMS

Sourcing images from GraphCMS

Sourcing images from Prismic

Summary

Part 2: Going Live

Chapter 6: Improving Your Site's Search Engine Optimization

Technical requirements

Introducing SEO

On-page search engine optimization

Creating an SEO component

Exploring meta previews

Open Graph metadata

Twitter metadata

Merging tags

Validating tags

Learning about XML sitemaps

Hiding your site from search engines

Summary

Chapter 7: Testing and Auditing Your Site

Technical requirements

Exploring unit testing

Testing simple components

Testing the SEO component

Testing Gatsby page components

Adding Git hooks for tests

Auditing core web vitals

Using Chrome's lighthouse tool

Using the web-vitals JavaScript package

Summary

Chapter 8: Web Analytics and Performance Monitoring

Technical requirements

Introducing website analytics

Privacy

Implementing page analytics

Adding Google Analytics

Using Fathom Analytics

Monitoring the performance of your site

Using Sentry.io analytics

Summary

Chapter 9: Deployment and Hosting

Technical requirements

Understanding build types

Common build errors

Your pre-deployment checklist

Platforms for deploying hybrid builds

Deploying to Gatsby Cloud Hosting

Platforms for deploying static builds

Deploying to Netlify

Deploying to Render

Deploying to Firebase

Serving a Gatsby site with reduced user access

Summary

Part 3: Advanced Concepts

Chapter 10: Creating Gatsby Plugins

Technical requirements

Understanding Gatsby plugins

Introducing local plugin development

Debugging local plugins

Creating source plugins

Creating theme plugins

Contributing to the plugin ecosystem

Pre-publish checklist

Publishing a plugin

Summary

Chapter 11: Creating Authenticated Experiences

Technical requirements

Routing and authentication in React applications

Private routes

Authentication using client-only routes within Gatsby

Site-wide authentication using context within Gatsby

Summary

Chapter 12: Using Real-Time Data

Technical requirements

Introduction to web sockets

Socket.io in action

Live site visitor count

Gaining further insights with rooms

Summary

Chapter 13: Internationalization and Localization

Technical requirements

Understanding localization and internationalization

Implementing routes for internationalization

Page translations for programmatic pages

Providing locale translations for single-instance pages

Summary

Why subscribe?

Other Books You May Enjoy

Packt is searching for authors like you

Part 1: Getting Started

Upon finishing this part, you should have a clear understanding of what Gatsby.js is. You should also be at a point where you can comfortably develop basic sites in Gatsby.js on your local machine.

In this part, we include the following chapters:

Chapter 1, An Overview of Gatsby.js for the UninitiatedChapter 2, Styling Choices and Creating Reusable LayoutsChapter 3, Sourcing and Querying Data (from Anywhere!)Chapter 4, Creating Reusable TemplatesChapter 5, Working with Images

Chapter 1: An Overview of Gatsby.js for the Uninitiated

In this book, we will take your existing React knowledge and supplement it with Gatsby.js (which we will refer to as Gatsby from now on) to create performant and accessible static sites. I hope to give you the tools you need to create better websites using Gatsby and get you to join the static site revolution. So, happy hacking!

This chapter starts with a brief historical look at the static web and why Gatsby was created. Then, we'll think about what Gatsby is and how it builds on React. Next, we'll go through some of the use cases of Gatsby and identify Gatsby's competitors. Finally, we'll set up a basic Gatsby project, having created our first few pages.

In this chapter, we will cover the following topics:

A brief history of the static webWhat is Gatsby?Gatsby use casesGatsby's competitorsSetting up a project

Technical requirements

The code present in this chapter can be found at https://github.com/PacktPublishing/Elevating-React-Web-Development-with-Gatsby-4/tree/main/Chapter01.

A brief history of the static web

Static sites have been around nearly as long as the internet itself. They are the original blueprint for any website – HyperText Markup Language (HTML), Cascading Style Sheets (CSS), and JavaScript (JS). In the 1990s, HTML was the only publishing mechanism for the web. To get content on the internet, you would have to create a static HTML file and expose it to the internet via a server. If you wanted to modify one of your web pages, you would need to change its corresponding HTML file directly.

While learning HTML is part of primary education these days, back in the 1990s, it was a novel skill to understand and write the language. Creating or editing content was costly, as you would require someone with this skill set for every modification. Luckily, Content Management Systems (CMSes) (WordPress, Drupal, and so on) soon swooped in to allow non-technical users to control a webpage's design and content. It also gave users the ability to store and manage files via a user interface. CMSs continue to be utilized today with increasing popularity. The number of websites using a CMS has risen from 23.6% to 63% in the last decade. Over 75 million sites use WordPress today – that's 30% of the web!

At an almost identical pace, frontend frameworks and libraries have gained notoriety. Building single-page applications became commonplace. Today, the most dominant UI library in the JS world is Facebook's React.js, which is a small library with a handful of functions but some big ideas – a virtual DOM, JavaScript Syntax Extension (JSX), and componentization. There is no denying how much impact React has had on web development. In 2020, 80% of JS developers had used it, and 70% of JS developers said they would use it again.

Frontend frameworks have entirely changed how developers approach web development, giving them the flexibility to focus on functionality over content and drastically speeding up their workflows. But you're only as fast as your slowest team member. The clunky nature of CMS platforms was revealed when developers started to employ these frameworks and integrate them with CMSs. Traditional CMS workflows made use of databases and environments that frontend frameworks had removed from the equation. Combining this with CMS security and bottleneck issues led to the rebirth of static sites.

Kyle Mathews, the founder of Gatsby, was a catalyst for this trend. He noticed that the expectations on website accessibility and performance increased dramatically. He observed apps investing millions of dollars in user experience. There is no denying that the disparity between a 2005 and 2015 website was significant. In a competitive environment such as the web, you have to have a product that can stand out. Mathews took a step back, identified gaps in existing tooling, and asked what the ideal product might be. This research is what led him to create Gatsby.

It's almost poetic that we have gone full circle and returned to static content because there is no beating it when it comes to speed and performance.

What is Gatsby?

Gatsby is a free, open source static site generator that harnesses React. Static site generators are software applications that create static pages from a template or component and supplement them with content from a source. Static site generators are an alternative to a more traditional database-driven CMS, such as WordPress. In these conventional systems, content is managed and stored in a database. When the server receives a particular URL request, the server retrieves data from the database, mixes it with a template file, and generates an HTML page as its response. Generating HTML on demand can be a time-consuming process and can leave the user twiddling their thumbs or, worse, leaving your site. Bounce rates (the percentage of visitors to a particular website who navigate away from the site after viewing only one page) hover below 10% for websites that take less than 3 seconds to load, but the number jumps to 24% for a 4-second load time and 38% for a 5-second load time.

Static site generators like Gatsby, on the other hand, generate pages during a build process. During this process, Gatsby brings in data to its GraphQL layer, where it can be queried in pages and templates. The requested data is then stored in JSON and accessed by the built pages, which are composed of HTML, JS, and CSS files. A user can deploy these generated pages to a server. When it receives a request, the server responds with predetermined, static, rendered HTML. As these static pages are generated at build time, they eliminate the latency that databases would introduce. You can even do away with web servers altogether and have your site served via a CDN pointing to a storage medium, such as an AWS Simple Storage Service (S3) bucket. The difference is striking; web experiences built with Gatsby are lightning fast, as nothing can be faster than sending static content.

Important Note

A static site can contain dynamic and exciting experiences! It is a common misconception that "static" means the site is stationary. This could not be further from the truth. The word "static" only refers to the manner in which files are retrieved by a client.

While Gatsby is known for static site generation, recent versions also include server-side and deferred static generation, rendering functionality for when static generation is not enough.

Aside from creating a blazing-fast user experience, Gatsby also has a focus on developer experience. As we learn and build, I'm sure you will start to recognize how easy it is to use. The way it achieves this can be broken down into four steps.

Community

Gatsby has an incredibly supportive community backing. At the time of writing, over 3,600 people have contributed to the Gatsby repository. This is further amplified by the plugin ecosystem surrounding Gatsby; the community has created more than 2,000+ plugins that abstract complex functionality that other developers may wish to use in their own projects. These plugins are distributed as packages stored on a JS repository, such as NPM, that can be added to your project in a few lines. They can extend your site by sourcing content, transforming data, creating pages, or theming your application.

Sourcing content from anywhere

Every day, the amount of data we need to combine to create experiences is rising. In traditional React applications, managing multiple sources of data could become a nightmare. Storing, massaging, merging, and querying data all require complex solutions that struggle to scale.

Gatsby does this differently. Whether you are sourcing data from a CMS, real-time database, or even a custom Application Programming Interface (API), you can merge all of this data into a unified data layer. The Gatsby community is constantly contributing source plugins to allow you to ingest data from your favorite sources with ease. Nine times out of ten, you won't need to write a single line of code to source your data, but for the times when you do, we will be covering plugin creation in Chapter 10, Creating Gatsby Plugins.

Once ingested into this data layer, we can explore and query all our sources of data in one place using a uniform data layer. Using the power of GraphQL, we can query our data in the same way when rendering pages regardless of their source. The GraphQL layer is transitory and doesn't exist after the application has been built, so doesn't affect the size of your production site. If GraphQL is something new to you, don't worry – I will be explaining how it works in Chapter 3, Sourcing and Querying Data (from Anywhere!).

Building tooling you already know

Often when we approach new technologies, we are faced with a steep learning curve as we understand new syntax and ways of thinking. In Gatsby, we build on your existing knowledge of React instead of starting from scratch. Underpinning all of our code is the same React component model many of you already know. You should feel pretty confident from the beginning, as the code should look familiar, and if you're not, Gatsby can also help you learn React from a more "content-driven" approach.

Supercharging web performance

As web developers, we can spend considerable time tinkering with websites to squeeze every ounce out of their performance. Sometimes, this can take as long, if not longer, than building the design. Also, performance gains can sometimes be undone instantly by a change to the site design outside of your control. It's because of this that some large organizations have dedicated teams to improve site performance. But it doesn't have to be this way! As we start to build together, you will see that load times go from seconds to milliseconds, and your site will feel far more responsive than a conventional React app. Gatsby has plenty of tricks up its sleeve that improve performance, some of which we will touch on at the end of this chapter. It also turns your site into a Progressive Web App (PWA) with just a few lines of code – if that's not cool, I don't know what is!

Important Note

An essential distinction between Gatsby and React is that Gatsby is a "framework," not a "library." When using a library, you control your application flow; you call it when you need it. When using a framework, however, there is an inversion of control. Frameworks command that you adhere to a particular flow and layout defined by them. Working within a framework can often be seen as a benefit, as any developer familiar with the framework will know where to find relevant files and code.

I hope you are beginning to see some of the great reasons why Gatsby is such a powerful tool. Let's now see it in action.

Gatsby use cases

You might be starting to realize that Gatsby could have applications across many different kinds of websites. Since Gatsby's v1 launch in 2017, the framework has been used in a multitude of different ways by companies both big and small. Here, I want to highlight some examples of use cases where Gatsby excels and suggest why companies may have chosen Gatsby for these sites.

Tip

While reading about these example sites here is great, I highly encourage you to visit them via your own device. One of Gatsby's best features is the speed of the sites it creates, and it is essential to experience this for yourself to understand the benefit.

Documentation sites

Documentation sites are a perfect use case for Gatsby as their content is primarily, if not entirely, static. Their content does not shift often either, with pages needing infrequent updates. Their static nature means that we can generate all page routes during the build process and load them onto a CDN, meaning that when a page is requested, the request is near-instant. It is for this reason that you see sites such as the official React documentation (https://reactjs.org) being made with Gatsby:

Figure 1.1 – The React documentation website

Due to the infrequent nature of updates to documentation pages, you can automate the build and deployment of your site as and when changes to documentation are made. With GitHub integrations or webhooks, you can get your documentation site to redeploy each change to a master branch or on a daily basis, for example. We will be exploring how to create these kinds of processes in Chapter 9, Deployment and Hosting.

Online courses

Online courses often have a unique structure – the majority of their content is in static learning modules, but they also require a small quantity of authenticated routes for logged-in user experiences.

Websites such as DesignCode.io (https://designcode.io/courses) utilize Gatsby for their static content, meaning their static pages are incredibly performant, and they then render authenticated routes on the client. While this does increase bundle size, as they need to ship more JS, the benefit of the fast static pages far outweighs the cost of heavier authenticated pages:

Figure 1.2 – The DesignCode.io website

One of the most popular sources of data for Gatsby is MDX. MDX is a powerful format that allows you to write JSX within Markdown. Why is it awesome? Because you can include React components alongside documentation with no hassle at all. React components can be far more interactive and dynamic than text, and as a result, it is a powerful format to create online courses on, as you can create content that is more enticing for the user. Perhaps a more interactive course is a more memorable one? We will be diving into MDX in detail in Chapter 3, Sourcing and Querying Data (from Anywhere!).

SaaS products

When selling Software as a Service (SaaS) online, your website's performance can be considered a reflection of your product's performance. As a result, having a clunky website can be the difference between your product being a success or not. As mentioned previously, this is an example where you could go down a rabbit hole to improve your site's performance. Companies such as Skupos (https://www.skupos.com/) use Gatsby to get more performance benefits for free. Gatsby also works wonders for Search Engine Optimization (SEO). As pages are prerendered, all your page content is available to web crawlers such as Googlebot to navigate to your site. The speed and SEO improvements help their product's website stand out and give the user confidence that they know what they are doing when it comes to technology:

Figure 1.3 – The Skupos website

Skupos also supplement their site pages with metadata and alt-text, which further aids web crawlers in understanding site content. The more web crawlers understand your site's content, the better your search engine ranking will be.

Design agencies and photo-heavy sites

In cases where your work is more visual, your site often needs to make use of large quantities of high-resolution images. We've all visited a website and felt like we were transported back to the dial-up days as we've waited for large image files to load. This common mistake is often amplified further by a large amount of cumulative layout shift that happens when loading images. Gracefully handling the image's loading state to avoid this can be a headache.

Gatsby performs magic for images within its application. It utilizes the sharp library (https://github.com/lovell/sharp) under the hood to convert your large images into smaller web-friendly sizes. When your website loads, it will first load in a smaller resolution version before blurring up to the maximum resolution required. This results in no layout shift and a far less "jumpy" experience for your site visitor. A great example of this is on the Call Bruno Creative Agency (https://www.callbruno.com/en/reelevant) website developed with Gatsby:

Figure 1.4 – The Call Bruno Creative Agency website

They use lots of imagery across their project pages, but the image load does not take you out of the experience. We will get into detail on handling images in Chapter 5, Working with Images.

By exploring these sites, we can see examples across industries where Gatsby is helping companies get ahead of their competition.

Gatsby's competitors

While this book focuses on Gatsby, it is crucial to understand that it is not the only React static site generator on the market. The competitor most often uttered in the same breath is Next.js.

Until recently, the key difference between Next.js and Gatsby was server-side rendering. Like Gatsby, a Next.js application can be hosted statically, but it also used to be able to server render pages where Gatsby could not. Instead of deploying a static build, a server is deployed to handle requests. When a page is requested, the server builds that page and caches it before sending it to the user. This means that subsequent requests to the resource are faster than the first call. As of version 4, Gatsby can have all of its pages prebuilt statically or it can create a hybrid build – a mixture of static and server-side rendered content. We will discuss this more in Chapter 9, Deployment and Hosting.

One major drawback to Next.js is its data security. When building Gatsby sites as static builds, data is only taken from the source at build time, and as the content is static, it is secure. Next.js keeps data stored on the server and, as such, it is easier to exploit. Next.js commonly requires more initialization if you wish to set it up via a server or using databases. This also means that there is more maintenance required in Next.js applications. Both Next.js and Gatsby have additional utilities to help with the handling of images. Gatsby, however, can make images more performant on statically rendered pages, while Next cannot.

The good news is that all static site generators follow a similar process. The skills and mentality you learn in this book are easily transferable to a different generator in the future should you decide you want to make the switch.

Now that we understand where Gatsby excels, let's start creating our first Gatsby project.

Setting up a project

In order to help you put into practice what you're learning, we will be building a project together. Throughout this book, we will be working to build a personal portfolio, something that every developer needs and therefore something I think will be relevant for most readers. The portfolio will contain blog pages to aid your learning in public, project pages to demonstrate your work, a stats page showcasing interesting metrics on your site, as well as many more features that will help your portfolio stand out from the crowd.

Throughout this book, you will be faced with options. We will discuss different implementations for styling your site, as well as data sources you may want to implement. This should give you the flexibility to align it with your current knowledge. Alternatively, you can throw yourself in the deep end – the choice is up to you. Everywhere there is a choice, I will also provide my personal recommendation for what might be best if you can't decide.

To see a finished version of the portfolio we will be building, visit this link:

https://elevating-react-with-gatsby.sld.codes/

Tip

Refer to the code repository (https://github.com/PacktPublishing/Elevating-React-Web-Development-with-Gatsby-4) that accompanies this book if you're struggling at any point. It includes a copy of the project as it should appear after every chapter.

To start using Gatsby, we need to ensure we have a few prerequisite tools set up on our machines. Most of these prerequisites are most likely already on your device if you are a React developer, although I would still encourage you to read through this list, as some of your tools may need an update.

Node.js version 14.15.0+

As of version 4.0, Gatsby supports all Node.js versions greater than 14.15.0. You can quickly check if you have Node.js installed by opening up a terminal window and typing the following:

node -v

If you have Node.js installed, this should print a version number. However, if you receive an error, you can download Node.js by navigating to the Node.js website (https://nodejs.org). Node.js comes bundled with npm, a package repository, package manager, and command-line tool that we will be using to install Gatsby.

Tip

You're most likely already using Node.js, and some of your pre-existing projects may require a different version than the requirements specified here. If you need to manage multiple versions of Node.js on the same device, you should check out the Node.js Version Manager (NVM)(https://github.com/nvm-sh/nvm). It gives you access to valuable commands, including installing new versions and switching between minor and major versions of Node.js.

Gatsby command-line interface

The Gatsby Command-Line Interface (CLI) is a tool built by the core Gatsby team; it allows you to perform standard functions, such as creating new Gatsby projects, setting up local development servers, and building your production site. Although you can use it on a per-project basis, it is far more common to install the CLI globally so that you can use its features across multiple Gatsby projects without having to install it as a package in each project – got to save that hard-drive space!

To install the CLI globally, npm install it with the global flag:

npm i -g gatsby-cli

To verify its installation, open up a terminal window and type the following:

gatsby --help

If running this provides a list of commands and does not error out, then you're good to go.

Important Note

Throughout this book, I use npm as my package manager. If you prefer Yarn, you can use the Yarn equivalent commands.

Directory and package setup

Here, we will begin to create the files and folders we need to start our project, as well as install necessary dependencies such as React and Gatsby.

First, create a folder to house our project. You can call it whatever you like. Throughout this book, I will refer to this folder as the root folder of the application. Open a terminal and navigate to your root folder. Initialize a new package in this folder by running the following:

npm init -y

With the package now initialized, let's install React and Gatsby:

npm i gatsby react react-dom

Open your root folder in your favorite Integrated Development Environment (IDE). You should notice that it now contains three new items, package.json, package-lock.json, and a