Gatsby.JS Quick Tutorial

[Fuente: https://www.gatsbyjs.com/tutorial/]

Gatsby.js Tutorials

The goal of this tutorial is to guide you through setting up and deploying your first Gatsby site using a starter template. As we walk through that process, we’ll introduce some more general web development topics, and go over the underlying structure of a Gatsby site.

The full tutorial is intended to be as accessible as possible to people without much web development experience (yet!) — no need to be an expert. If you prefer to jump straight to code, feel free to skip the step-by-step tutorial and see the quick start page.

Gatsby fundamentals

  1. Set up your development environment: We’ll introduce you to core technologies that power Gatsby, and guide you through setting up your development environment.
  2. Get to know Gatsby building blocks: Starting new projects, developing, and deploying sites.
  3. Introduction to using CSS in Gatsby: Explore libraries like Typography.js and CSS Modules.
  4. Building nested layouts in Gatsby: Layouts are sections of your site that are reused across multiple pages like headers and footers.

Intermediate tutorials

In these intermediate tutorials, you’ll learn how to pull data from almost anywhere into your Gatsby site with GraphQL.

  1. Querying for data in a blog: Create a blog and use a GraphQL query to pull your site title into the blog header.
  2. Source plugins and rendering queried data: Use a source plugin to pull Markdown blog posts into your site and create an index page with a list of blog posts.
  3. Transformer plugins: Use a transformer plugin to transform your Markdown blog posts into a form the blog can render.
  4. Programmatically create pages from data: Learn how to programmatically create a set of pages for your blog posts.
  5. Preparing a site to go live: Learn how to audit your site for performance and best practices for accessibility, SEO, and more.

Mac installation instructions

Required: XCode Command line tools + Node last version +  Homebrew

Using the Gatsby CLI

The Gatsby CLI tool lets you quickly create new Gatsby-powered sites and run commands for developing Gatsby sites. It is a published npm package.

The Gatsby CLI is available via npm and should be installed globally by running:

npm install -g gatsby-cli

Note: when you install Gatsby and run it for the first time, you’ll see a short message notifying you about anonymous usage data that is being collected for Gatsby commands, you can read more about how that data is pulled out and used in the telemetry doc.

See the available commands:

gatsby --help

Create a Gatsby site

Now you are ready to use the Gatsby CLI tool to create your first Gatsby site. Using the tool, you can download “starters” (partially built sites with some default configuration) to help you get moving faster on creating a certain type of site. The “Hello World” starter you’ll be using here is a starter with the bare essentials needed for a Gatsby site.

Open up your terminal.Create a new site from a starter:

gatsby new hello-world https://github.com/gatsbyjs/gatsby-starter-hello-world

💡 What happened? new is a gatsby command to create a new Gatsby project.
Here, hello-world is an arbitrary title — you could pick anything. The CLI tool will place the code for your new site in a new folder called “hello-world”.
Lastly, the GitHub URL specified points to a code repository that holds the starter code you want to use.

💡 Depending on your download speed, the amount of time this takes will vary. For brevity’s sake, the gif below was paused during part of the install

Change into the working directory:

cd hello-world

Start the development mode:

gatsby develop

💡 This command starts a development server. You will be able to see and interact with your new site in a development environment — local (on your computer, not published to the internet). View your site locally: Open up a new tab in your browser and navigate to http://localhost:8000/. Congrats! This is the beginning of your very first Gatsby site! 🎉

Familiarizing with Gatsby pages

Open up the /src directory in your code editor. Inside is a single directory: /pages.

Open the file at src/pages/index.js. The code in this file creates a component that contains a single div and some text — appropriately, “Hello world!”

✋ Using page components

Any React component defined in src/pages/*.js will automatically become a page. Let’s see this in action.

You already have a src/pages/index.js file that came with the “Hello World” starter. Let’s create an about page. Create a new file at src/pages/about.js, copy the following code into the new file, and save.
src/pages/about.js

import React from "react";
export default function About() {
    return (
        <div style={{ color: `teal` }}>
            <h1>About Gatsby</h1>
            <p>Such wow. Very React.</p>
        </div>
    );
}

Navigate to http://localhost:8000/about/. Just by putting a React component in the src/pages/about.js file, you now have a page accessible at /about.

✋ Using sub-components

Let’s say the homepage and the about page both got quite large and you were rewriting a lot of things. You can use sub-components to break the UI into reusable pieces. Both of your pages have <h1> headers — create a component that will describe a Header.

Create a new directory at src/components and a file within that directory called header.js. Add the following code to the new src/components/header.js file.

import React from "react";
export default function Header() {
    return <h1>This is a header.</h1>;
}

Modify the about.js file to import the Header component. Replace the h1 markup with <Header />:
src/pages/about.js

import React from "react";
import Header from "../components/header";
export default function About() {
    return (
        <div style={{ color: `teal` }}>
            <Header />
            <p>Such wow. Very React.</p>
        </div>
    );
}

In the browser, the “About Gatsby” header text should now be replaced with “This is a header.” But you don’t want the “About” page to say “This is a header.” You want it to say, “About Gatsby”.

Head back to src/components/header.js and make the following change:
src/components/header.js

import React from "react";
export default function Header(props) {
    return <h1>{props.headerText}</h1>;
}

Head back to src/pages/about.js and make the following change:
src/pages/about.js

import React from "react";
import Header from "../components/header";
export default function About() {
    return (
        <div style={{ color: `teal` }}>
            <Header headerText="About Gatsby" />
            <p>Such wow. Very React.</p>
        </div>
    );
}

You should now see your “About Gatsby” header text again!

Linking between pages
You’ll often want to link between pages — Let’s look at routing in a Gatsby site.

✋ Using the <Link /> component

Open the index page component (src/pages/index.js), import the <Link /> component from Gatsby, add a <Link /> component above the header, and give it a to property with the value of “/about/” for the pathname:
src/pages/index.js

import { Link } from "gatsby";
import React from "react";
import Header from "../components/header";

export default function Home() {
    return (
        <div style={{ color: `purple` }}>
            <Link to="/about/">About</Link>
            <Header headerText="Hello Gatsby!" />
            <p>What a world.</p>
            <img src="https://source.unsplash.com/random/400x200" alt="" />
        </div>
    );
}

Using global styles

Every site has some sort of global style. This includes things like the site’s typography and background colors. These styles set the overall feel of the site — much like the color and texture of a wall sets the overall feel of a room.

Creating global styles with standard CSS files

One of the most straightforward ways to add global styles to a site is using a global .css stylesheet.

Add styles to a CSS file

  1. Create a .css file in your new project:
    1. src/styles/global.css
  2. Define some styles in the global.css file:
  3. html {
      background-color: lavenderblush;
    }
  4. Include the stylesheet in gatsby-browser.js

    1. Create the gatsby-browser.js in root folder
    2. Import your recently-created stylesheet in the gatsby-browser.js file:
    3. import "./src/styles/global.css"

       

Tip: This part of the tutorial has focused on the quickest and most straightforward way to get started styling a Gatsby site — importing standard CSS files directly, using gatsby-browser.js. In most cases, the best way to add global styles is with a shared layout componentCheck out the docs for more on that approach.

Using component-scoped CSS

So far, we’ve talked about the more traditional approach of using standard CSS stylesheets. Now, we’ll talk about various methods of modularizing CSS to tackle styling in a component-oriented way.

Let’s explore CSS Modules. Quoting from the CSS Module homepage:

CSS Module is a CSS file in which all class names and animation names are scoped locally by default.

CSS Modules are very popular because they let you write CSS normally but with a lot more safety. The tool automatically generates unique class and animation names, so you don’t have to worry about selector name collisions.

Gatsby works out of the box with CSS Modules. This approach is highly recommended for those new to building with Gatsby (and React in general).

✋ Build a new page using CSS Modules

In this section, you’ll create a new page component and style that page component using a CSS Module.

First, create a new Container component.

  1. Create a new directory at src/components and then, in this new directory, create a file named container.js and paste the following:
    1. import React from "react";
      import containerStyles from "./container.module.css";
      export default function Container({ children }) {
          return <div className={containerStyles.container}>{children}</div>;
      }
      

       

You’ll notice you imported a CSS module file named container.module.css. Let’s create that file now.

  1. In the same directory (src/components), create a container.module.css file and copy/paste the following:
    1. .container {
          margin: 3rem auto;
          max-width: 600px;
      }
      

       

You’ll notice that the file name ends with .module.css instead of the usual .css. This is how you tell Gatsby that this CSS file should be processed as a CSS module rather than plain CSS.
  1. Create a new page component by creating a file at src/pages/about-css-modules.js:
    1. import React from "react";
      import Container from "../components/container";
      export default function About() {
          return (
              <Container>
                  <h1>About CSS Modules</h1>
                  <p>CSS Modules are cool</p>
              </Container>
          );
      }

       

Gatsby Config API

Site configuration options for a Gatsby site are placed in a file at the root of the project folder called gatsby-config.js.

Note: There are many sample configs which may be helpful to reference in the different Gatsby Example Websites.

Configuration options

Options available to set within gatsby-config.js include:
1. siteMetadata (object)
2. plugins (array)
3. pathPrefix (string)
4. polyfill (boolean)
5. mapping (object)
6. proxy (object)
7. developMiddleware (function)

siteMetadata
When you want to reuse common pieces of data across the site (for example, your site title), you can store that data in siteMetadata:
gatsby-config.js

/**
 * Configure your Gatsby site with this file.
 *
 * See: https://www.gatsbyjs.com/docs/gatsby-config/
 */

module.exports = {
    siteMetadata: {
        title: `Gatsby`,
        siteUrl: `https://www.gatsbyjs.com`,
        description: `Blazing fast modern site generator for React`,
    },

    plugins: [],
};

This way you can store it in one place, and pull it whenever you need it. If you ever need to update the info, you only have to change it here.
sample usage

import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"

export default function About({ data }) {
  return (
    <Layout>
      <h1>About {data.site.siteMetadata.title}</h1>
      <p>
        We're the only site running on your computer dedicated to showing the
        best photos and videos of pandas eating lots of food.
      </p>
    </Layout>
  )
}

export const query = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
  }
`

 

Plugins
Plugins are Node.js packages that implement Gatsby APIs. The config file accepts an array of plugins. Some plugins may need only to be listed by name, while others may take options (see the docs for individual plugins).
gatsby-config.js

module.exports = {
    plugins: [
        `gatsby-plugin-react-helmet`,
        {
            resolve: `gatsby-source-filesystem`,
            options: {
                name: `docs`,
                path: `${__dirname}/../docs/`,
            },
        },
    ],
};

See more about Plugins for more on utilizing plugins, and to see available official and community plugins.

pathPrefix
It’s common for sites to be hosted somewhere other than the root of their domain. Say you have a Gatsby site at example.com/blog/. In this case, you would need a prefix (/blog) added to all paths on the site.
gatsby-config.js

module.exports = {
    pathPrefix: `/blog`,
};

See more about Adding a Path Prefix.

Polyfill
Gatsby uses the ES6 Promise API. Because some browsers don’t support this, Gatsby includes a Promise polyfill by default.
If you’d like to provide your own Promise polyfill, you can set polyfill to false.
gatsby-config.js

module.exports = {
    polyfill: false,
};

See more about Browser Support in Gatsby.

Mapping node types
Gatsby includes an advanced feature that lets you create “mappings” between node types.

Note: Gatsby v2.2 introduced a new way to create foreign-key relations between node types with the @link GraphQL field extension.

For instance, imagine you have a multi-author markdown blog where you want to “link” from each blog post to the author information stored in a YAML file named author.yaml:

MD

---
title: A blog post
author: Kyle Mathews
---

A treatise on the efficacy of bezoar for treating agricultural pesticide poisoning.

author.yaml

- id: Kyle Mathews
bio: Founder @ GatsbyJS. Likes tech, reading/writing, founding things. Blogs at bricolage.io.
twitter: "@kylemathews"

You can map between the author field in frontmatter to the id in the author.yaml objects by adding to your gatsby-config.js:

module.exports = {
    plugins: [],
    mapping: {
        "MarkdownRemark.frontmatter.author": `AuthorYaml`,
    },
};

You may need to install the appropriate file transformer (in this case YAML) and set up gatsby-source-filesystem properly for Gatsby to pick up the mapping files. This applies to other file types later mentioned in this segment as well.
Gatsby then uses this mapping when creating the GraphQL schema to enable you to query data from both sources:

GRAPHQL

query($slug: String!) {
  markdownRemark(fields: { slug: { eq: $slug } }) {
    html
    fields {
      slug
    }
    frontmatter {
      title
      author {
        # This now links to the author object
        id
        bio
        twitter
      }
    }
  }
}

Mapping can also be used to map an array of ids to any other collection of data. For example, if you have two JSON files experience.json and tech.json as follows:
experience.json

[
  {
    "id": "companyA",
    "company": "Company A",
    "position": "Unicorn Developer",
    "from": "Dec 2016",
    "to": "Present",
    "items": [
      {
        "label": "Responsibility",
        "description": "Being an unicorn"
      },
      {
        "label": "Hands on",
        "tech": ["REACT", "NODE"]
      }
    ]
  }
]

tech.json

[
  {
    "id": "REACT",
    "icon": "facebook",
    "color": "teal",
    "label": "React"
  },
  {
    "id": "NODE",
    "icon": "server",
    "color": "green",
    "label": "NodeJS"
  }
]

 

And then add the following rule to your gatsby-config.js:

module.exports = {
  plugins: [...],
  mapping: {
    'ExperienceJson.items.tech': `TechJson`
  },
}

You can query the tech object via the referred ids in experience:

query {
  experience: allExperienceJson {
    edges {
      node {
        company
        position
        from
        to
        items {
          label
          description
          link
          tech {
            label
            color
            icon
          }
        }
      }
    }
  }
}

Mapping also works between Markdown files. For example, instead of having all authors in a YAML file, you could have info about each author in a separate Markdown file:

MD

---
author_id: Kyle Mathews
twitter: "@kylemathews"
---

Founder @ GatsbyJS. Likes tech, reading/writing, founding things. Blogs at bricolage.io.

And then add the following rule to your gatsby-config.js:

module.exports = {
  plugins: [...],
  mapping: {
    'MarkdownRemark.frontmatter.author': `MarkdownRemark.frontmatter.author_id`
  },
}

Similarly to YAML and JSON files, mapping between Markdown files can also be used to map an array of ids.

Proxy
Setting the proxy config option will tell the develop server to proxy any unknown requests to your specified server. For example:
gatsby-config.js

module.exports = {
  proxy: {
    prefix: "/api",
    url: "http://examplesite.com/api/",
  },
}

See more about Proxying API Requests in Develop.

Advanced proxying with developMiddleware
See more about adding develop middleware.

Deploying a Gatsby site

Gatsby is a modern site generator, which means there are no servers to set up or complicated databases to deploy. Instead, the Gatsby build command produces a directory of static HTML and JavaScript files which you can deploy to a static site hosting service.

Plugin & Theme tutorials

Gatsby plugins are a way to encapsulate, re-use, and compose functionality, such as data sourcing.

Gatsby themes are a type of plugin which abstracts your default configuration (shared functionality, data sourcing, design) out of your site and into an installable package.

Learn how to build and use plugins and themes step-by-step in the Plugin and Theme Tutorials.