One place for hosting & domains

      Gatsby

      How To Set Up Your First Gatsby Website


      Introduction

      Gatsby is a React framework that allows you to create static and serverless apps. Gatsby websites are different from traditional websites because they are usually deployed on a content delivery network (CDN) and are content agnostic. The advantage of deploying from a CDN is that there is less latency and websites are usually served to the client faster.

      Gatsby is often described as a content mesh. A content mesh means that as the user, you are able to pull data from diverse sources such as a WordPress site, a CSV file, and a variety of external APIs; as a result Gatsby is data agnostic. This is different from a traditional content management system (CMS) like WordPress and Drupal, where the data usually comes from a single source—a database. When you build an application upon Gatsby you don’t have to worry about maintaining and provisioning a database. Additionally, when you’re using Gatsby you’re able to build on a framework that is known for its speed and flexibility.

      These serverless websites are also known as a JAMStack. In a JAMStack architecture, there is still a server involved, but the developer doesn’t need to provision or maintain the server. Some developers see serverless as a desirable feature because they can focus more of their attention on the business logic of their application. For example, if they were creating an e-commerce store, they could focus on the code that is directly related to creating and selling products. JAMStack helps developers quickly develop websites that are more secure, more performant, and cheaper to deploy than traditional CMS frameworks.

      In this tutorial, you will:

      • Install the Gatsby Starter default template.
      • Modify metadata in gatsby config.
      • Run the development server and view the Gatsby site locally.
      • Get a short introduction to JSX and Gatsby’s image optimization capabilities.

      By the end of this tutorial, you will be able to create and modify a Gatsby site. You are going to get your first Gatsby e-commerce site up and running. Keep in mind that you will make this site on your local machine and you will not deploy it.

      Prerequisites

      Step 1 — Installing Gatsby and Creating a New Project

      In this step you will install a new Gatsby site from a template. Gatsby provides users with starter templates, so you don’t have to worry about building a website from nothing.

      Download the Gatsby CLI package. This Gatsby command-line interface will allow you to create and customize a new site:

      • npm install -g gatsby-cli

      The -g flag means you are installing the Gatsby command-line interface globally as opposed to locally. This will allow you to use the tool in any directory.

      Note: On some systems such as Ubuntu 18.04, installing an npm package globally can result in a permission error, which will interrupt the installation. Since it is a security best practice to avoid using sudo with npm install, you can instead resolve this by changing npm’s default directory. If you encounter an EACCES error, follow the instructions at the official npm documentation.

      If you type gatsby help you will find several commands that you can use in creating your Gatsby site:

      This will give the following output:

      Output

      Usage: gatsby <command> [options] Commands: gatsby develop Start development server. Watches files, rebuilds, and hot reloads if something changes gatsby build Build a Gatsby project. gatsby serve Serve previously built Gatsby site. gatsby info Get environment information for debugging and issue reporting gatsby clean Wipe the local gatsby environment including built assets and cache gatsby repl Get a node repl with context of Gatsby environment, see (https://www.gatsbyjs.org/docs/gatsby-repl/) gatsby new [rootPath] [starter] Create new Gatsby project. gatsby plugin Useful commands relating to Gatsby plugins gatsby telemetry Enable or disable Gatsby anonymous analytics collection. ...

      Here are the most important commands for this tutorial:

      • gatsby new creates a brand new site. If you use gatsby new by itself you will get a barebones site. The more common way to use gatsby new is to combine it with a starter template, which is what you will do in this tutorial.

      • gatsby develop starts the development server. Throughout this tutorial you will use gatsby develop to see your site locally on port :8000.

      • gatsby build bundles static files and assets and creates a production build of your application.

      You have now installed the Gatsby command-line tools, but you still don’t have a site. One of the advantages of Gatsby is that you don’t have to code a website from scratch. Gatsby has several starter templates that you can use to get your website up and running. There are hundreds of templates out there, and many of these contributions come from the community. For this tutorial, you are going to use one of Gatsby’s official starter templates, Gatsby Starter Default.

      The first thing you will do is install a Gatsby starter via your terminal:

      • gatsby new gatsby-starter-default https://github.com/gatsbyjs/gatsby-starter-default

      gatsby new creates a new site. This tutorial will use the gatsby-starter-default template, and will name the project after the template.

      The following output in the command line means you have successfully installed a Gatsby starter template:

      Output

      ... Your new Gatsby site has been successfully bootstrapped. Time to change into the directory cd gatsby-starter-default gatsby develop

      gatsby-starter-default is the name of your new directory. You will now change into gatsby-starter-default and list the contents of the directory:

      • cd gatsby-starter-default && ls

      This will give the following output:

      Output

      LICENSE gatsby-browser.js gatsby-node.js node_modules public yarn.lock README.md gatsby-config.js gatsby-ssr.js package.json src

      The important files you will modify in this tutorial include:

      • gatsby-config.js contains your site-wide customizations. This is where you will modify metadata and add Gatsby plugins.

      • src directory contains all of the pages, images, and components that make up the website. In React, components are isolated parts of a website. For instance, in your website, the index page is made up of layout, image, and seo components.

      Now that you have created a new Gatsby project and explored the file structure, you are ready to go into your project and customize your site’s metadata.

      If you want to have your website discovered by a search engine, it is important to correctly format your metadata. In this section, you will configure the title, description, and author metadata in your application.

      /gatsby config is Gatsby’s configuration file. This is where you will find the site siteMetadata object. The site metadata helps boosts your site’s SEO and makes it more discoverable by search engines.

      Open gatsby-config.js in a text editor tp view Gatsby’s configuration. nano is the name of the text editor this tutorial will use to view the Gatsby config file, but you can use the editor of your choice:

      The following is gatsby-config.js with the configurations that come with the Gatsby Default Starter template:

      gatsby-config.js

      module.exports = {
        siteMetadata: {
          title: `Gatsby Default Starter`,
          description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
          author: `@gatsbyjs`,
        },
        plugins: [
          `gatsby-plugin-react-helmet`,
          {
            resolve: `gatsby-source-filesystem`,
            options: {
              name: `images`,
              path: `${__dirname}/src/images`,
            },
          },
          `gatsby-transformer-sharp`,
          `gatsby-plugin-sharp`,
          {
            resolve: `gatsby-plugin-manifest`,
            options: {
              name: `gatsby-starter-default`,
              short_name: `starter`,
              start_url: `/`,
              background_color: `#663399`,
              theme_color: `#663399`,
              display: `minimal-ui`,
              icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
            },
          },
          // this (optional) plugin enables Progressive Web App + Offline functionality
          // To learn more, visit: https://gatsby.dev/offline
          // `gatsby-plugin-offline`,
        ],
      }
      

      The Gatsby config file is also home to your plugins. Plugins are packages you install to add functionality to your Gatsby app. This installation of Gatsby comes with the gatsby-plugin-react-helmet, gatsby-transformer-sharp, gatsby-plugin-sharp, and gatsby-plugin-manifest plugins.

      Every Gatsby Default Starter template contains the same generic metadata. You are going to personalize this data and start the process of making this site your own.

      Replace the text for title, description, and author with the following highlighted code:

      gatsby-config.js

      module.exports = {
        siteMetadata: {
          title: `Getting Started with Gatsby`,
          description: `A tutorial that goes over Gatsby development`,
          author: `@digitalocean`,
        },
        plugins: [
          `gatsby-plugin-react-helmet`,
          {
            resolve: `gatsby-source-filesystem`,
            options: {
              name: `images`,
              path: `${__dirname}/src/images`,
            },
          },
          `gatsby-transformer-sharp`,
          `gatsby-plugin-sharp`,
          {
            resolve: `gatsby-plugin-manifest`,
            options: {
              name: `gatsby-starter-default`,
              short_name: `starter`,
              start_url: `/`,
              background_color: `#663399`,
              theme_color: `#663399`,
              display: `minimal-ui`,
              icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
            },
          },
          // this (optional) plugin enables Progressive Web App + Offline functionality
          // To learn more, visit: https://gatsby.dev/offline
          // `gatsby-plugin-offline`,
        ],
      }
      

      Save and exit the file.

      Now when Google or another search engine crawls your website, it will retrieve the data associated with your app. You have changed the metadata; next you will change one of the website’s pages.

      Step 3 — Modifying the Index Page

      In this section you are going to learn about JSX, change the markup on the index page, add an image, and run your Gatsby site locally.

      It is time to see what the Gatsby website looks like in your browser. Open a new window in the terminal and enter gatsby develop in the command line to view the local version of the site:

      The gatsby develop command starts the development server. If you head over to the browser you can access your site at localhost:8000:

      This is an image of the Gatsby homepage

      You are going to change the markup on the page to make it look more like the content you would find on an e-commerce site. Change the markup on the index page:

      This is what you will find in the text editor:

      src/pages/index.js

      import React from "react"
      import { Link } from "gatsby"
      
      import Layout from "../components/layout"
      import Image from "../components/image"
      import SEO from "../components/seo"
      
      const IndexPage = () => (
        <Layout>
          <SEO title="Home" />
          <h1>Hi people</h1>
          <p>Welcome to your new Gatsby site.</p>
          <p>Now go build something great.</p>
          <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
            <Image />
          </div>
          <Link to="/page-2/">Go to page 2</Link> <br />
          <Link to="/using-typescript/">Go to "Using TypeScript"</Link>
        </Layout>
      )
      
      export default IndexPage
      

      The code here is JSX. JSX allows you to write HTML elements in JavaScript. If you want a more comprehensive overview of JSX, go to our JSX tutorial.

      In the text editor, replace <h1>Hi People</h1> with <h1>Hello Shoppers, we are open for business!<h1> and <p>Welcome to your new Gatsby site.</p> with <p>We sell fresh fruit.</p>. Delete <p>Now go build something great.</p>:

      src/pages/index.js

      import React from "react"
      import { Link } from "gatsby"
      
      import Layout from "../components/layout"
      import Image from "../components/image"
      import SEO from "../components/seo"
      
      const IndexPage = () => (
        <Layout>
          <SEO title="Home" />
          <h1>Hello Shoppers, we are open for business!</h1>
          <p>We sell fresh fruit.</p>
          <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
            <Image />
          </div>
          <Link to="/page-2/">Go to page 2</Link> <br />
          <Link to="/using-typescript/">Go to "Using TypeScript"</Link>
        </Layout>
      )
      
      export default IndexPage
      

      Save your changes. There is no need to start and stop the development server because Gatsby comes with hot reloading. Hot reloading refreshes the files in your app that you’ve changed:

      A screenshot of your website with the new changes

      You are now going to change the image from the Gatsby astronaut to Sammy the Shark. Open the image in your browser and download the image to your src/images folder in your Gatsby project. Save the image as sammy-shark.jpeg.

      Double check to see if the Sammy the Shark image is in the right folder. Navigate to the imagesfolder:

      After you have made your way to the images directory, check if sammy-shark.jpeg is in the images folder:

      ls is the command for list. You are listing all the files found in the images folder:

      Output

      gatsby-astronaut.png gatsby-icon.png sammy-shark.jpeg

      Now that you have confirmed that the file is there, you will open image.js in your favorite text editor. You are about to swap out the Gatsby astronaut image with Sammy the Shark.

      First, return to your src directory:

      Now open the image.js component:

      Replace gatsby-astronaut.png with sammy-shark.jpeg:

      src/components/image.js

      import React from "react"
      import { useStaticQuery, graphql } from "gatsby"
      import Img from "gatsby-image"
      
      /*
       * This component is built using `gatsby-image` to automatically serve optimized
       * images with lazy loading and reduced file sizes. The image is loaded using a
       * `useStaticQuery`, which allows us to load the image from directly within this
       * component, rather than having to pass the image data down from pages.
       *
       * For more information, see the docs:
       * - `gatsby-image`: https://gatsby.dev/gatsby-image
       * - `useStaticQuery`: https://www.gatsbyjs.org/docs/use-static-query/
       */
      
      const Image = () => {
        const data = useStaticQuery(graphql`
          query {
            placeholderImage: file(relativePath: { eq: "sammy-shark.jpeg" }) {
              childImageSharp {
                fluid(maxWidth: 300) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
          }
        `)
      
        return <Img fluid={data.placeholderImage.childImageSharp.fluid} />
      }
      
      export default Image
      

      Gatsby uses GraphQL to make data queries, and here the image.js file in Gatsby queries the PNG image and optimizes it. In this snippet, Gatsby scales the image size of sammy-shark.jpeg to a maximum width of 300. You can read more about how Gatsby formats images here.

      file() is a function that opens the file where "sammy-shark.jpeg" is located. relativePath tells you where the image is in relation to where you are located—or the present working directory (pwd). eq is the filter value, a part of GraqhQL.

      Save the file. The server will restart, and you will find Sammy the Shark on your Gatsby page:

      This is the final version of our Gatsby e-commerce site

      You now have your Gatsby e-commerce site up and running locally.

      Conclusion

      In this tutorial, you created your first Gatsby website. You have learned how to set up a basic Gatsby site on your local machine. Now that you can create and customize a Gatsby app, the next step is to deploy your Gatsby e-commerce site.



      Source link

      Faster WordPress Sites With Gatsby


      Talk about the latest cutting-edge web technologies, and you find some impressive names like React.js, Vue.js, Next.js, and so on. They have opened new gateways and approaches to building websites that can serve content to users quickly.

      One framework that can increase overall site speed and load times is Gatsby.js.

      Goals of a Fast Website

      A website that loads fast entails the following perks and benefits for developers:

      • Traffic and Engagement: You get more site visitors on a fast site, which translates to better ROI and user engagement.
      • Page Ranks: Fast websites earn higher browser rankings.

      Improving Site Speed With Gatsby.js and WordPress

      Gatsby.js is a free and open-source React.js-based framework that helps developers build websites and applications. It is part of a general trend toward JAMstack (JavaScript APIs Markup) sites, which aim to increase overall site speed and load times.

      But where does Gatsby fit with WordPress, one of the most widely-used CMS options available today? Despite its usability and robust community, WordPress can pose challenges to building a modern frontend, for the following reasons:

      • Updates and Changes: WordPress is regularly updated, but it still lacks parity with other rapidly-changing front-end technologies. Staying up-to-date with these technologies adds an additional burden for the developer.
      • Continuous Integration and Deployment: Right now, few Continuous Integration/Deployment (CI/CD) options exist in the WordPress ecosystem.
      • Integration Costs: It can be challenging to integrate some of the latest front-end technologies with a WordPress application.

      Using Gatsby can address some of these limitations. In the following steps, we will show you how to integrate Gatsby with WordPress to take full advantage of both. First, we are going to configure a basic Gatsby project setup. Then, we’ll use it to fetch data from our WordPress site.

      Integrating Gatsby.js with WordPress

      First, we will set up a demo Gatsby project.

      Install the Gatsby CLI by typing the following command in your terminal:

      • npm install -g gatsby-cli

      Next, create a new Gatsby site with the following command:

      To access your site folder contents, type the following:

      Finally, start the development server to begin building your site:

      Installing the gatsby-source-wordpress Plugin

      Assuming that you have a WordPress site already set up, and you would like to have a frontend built with Gatsby.js, all you need to do is pull your existing site data into your static Gatsby site. You can do that with the gatsby-source-wordpress plugin.

      This tutorial uses the default WordPress REST API site, though you are free to use a pre-existing WordPress setup if you have one.

      Inside your terminal, type the following to install this plugin:

      • npm install gatsby-source-wordpress

      Configuring the Plugin

      Inside your gatsby-config.js file, the main Gatsby configuration file, you will add some WordPress-specific configuration options. These include your WordPress site’s baseUrl, the preferred HTTP protocol, and settings pertaining to the Advanced Custom Fields (ACF) plugin. The includedRoutes fields specifies the data we want to fetch.

      Using the demo WordPress site from the step above, the current frontend looks like this:

      For the purposes of this tutorial, add the following code to a file called gatsby-config.js:

      module.exports = {
        // ...
        plugins: [
          // ...
          {
              resolve: `gatsby-source-wordpress`,
              options: {
                  // Your WordPress source.
                  baseUrl: `demo.wp-api.org`,
                  protocol: `https`,
                  // Only fetches posts, tags and categories from the baseUrl.
                  includedRoutes: ['**/posts', '**/tags', '**/categories'],
                  // Not using ACF so putting it off.
                  useACF: false
              }
          },
        ],
      }
      

      Using Fetched WordPress Data

      Once your Gatsby site is fetching data from your WordPress source URL, it’s time to create your site pages. This is done by implementing the createPages API in the gatsby-node.jsfile, which makes the fetched data available to queries from GraphQL. At build time, the gatsby-source-wordpress plugin fetches your data, and uses it to ”automatically infer a GraphQL schema” which you can query against.

      Add the following code to a file called gatsby-node.js:

      /**
       * Implement Gatsby's Node APIs in this file.
       *
       * See: https://www.gatsbyjs.org/docs/node-apis/
       */
      
      // You can delete this file if you're not using it
      
      const path = require(`path`);
      const slash = require(`slash`);
      
      /** STEP #1: Implement the Gatsby API “createPages”. This is
       * called after the Gatsby bootstrap is finished so you have
       * access to any information necessary to programmatically
       * create pages.
       * Will create pages for WordPress pages (route : /{slug})
       * Will create pages for WordPress posts (route : /post/{slug})
       */
      exports.createPages = async ({ graphql, actions }) => {
          const { createPage } = actions;
      
          // STEP #2: Query all WordPress Posts Data.
          /** The “graphql” function allows us to run arbitrary
           * queries against the local Gatsby GraphQL schema. Think of
           * it like the site has a built-in database constructed
           *  from the fetched data that you can run queries against.
           */
          const result = await graphql(`
              {
                  allWordpressPost {
                      edges {
                          node {
                              id
                              slug
                              status
                              template
                              format
                          }
                      }
                  }
              }
          `);
      
          // Check for any errors
          if (result.errors) {
              throw new Error(result.errors);
          }
      
          // Access query results via object destructuring.
          const { allWordpressPost } = result.data;
      
          const postTemplate = path.resolve(`./src/templates/post.js`);
      
          // STEP #3: Create pages in Gatsby with WordPress Posts Data.
          /**
           * We want to create a detailed page for each
           * post node. We'll just use the WordPress Slug for the slug.
           * The Post ID is prefixed with 'POST_'
           */
          allWordpressPost.edges.forEach(edge => {
              createPage({
                  path: `/${edge.node.slug}/`,
                  component: slash(postTemplate),
                  context: {
                      id: edge.node.id
                  }
              });
          });
      };
      

      This will iterate through existing WordPress post data.

      Step #4: Creating a post.js Template

      Next, we will create a folder for templates, where you can add files for posts, pages, and layouts. For now, we will create a post.js file to fetch posts from our WordPress site.

      Add the following code to the file:

      import { graphql } from 'gatsby';
      import PropTypes from 'prop-types';
      import React, { Component } from 'react';
      import Layout from '../layouts';
      
      class PostTemplate extends Component {
          render() {
              const post = this.props.data.wordpressPost;
      
              // STEP #5: Use title and content in Gatsby.
              return (
                  <Layout>
                      <h1 dangerouslySetInnerHTML={{ __html: post.title }} />
                      <div dangerouslySetInnerHTML={{ __html: post.content }} />
                  </Layout>
              );
          }
      }
      
      PostTemplate.propTypes = {
          data: PropTypes.object.isRequired,
          edges: PropTypes.array
      };
      
      export default PostTemplate;
      
      // STEP #4: Get current WP Post data via ID.
      export const pageQuery = graphql`
          query($id: String!) {
              wordpressPost(id: { eq: $id }) {
                  title
                  content
              }
          }
      `;
      

      Examining the Final Result

      To start the development server and view the final result, type the following command in your terminal:

      You will get the link where you can access the site locally, along with other details like the number of posts, categories, and tags that are being fetched.

      Here’s a GIF that demonstrates what this will look like:


      Let’s take a look at this revamped front-end which is now powered with Gatsby.js and a WordPress back-end:

      You can see how our application is only fetching the required data from the WordPress site. This includes posts, tags and categories. To retrieve other types of data like widgets or comments, you will need to add the appropriate values to the includedRoutes option.

      Conclusion

      By following this tutorial, you now have a WordPress application backend integrated with a Gatsby.js frontend. Gatsby provides a fast web experience and brings with it added benefits that can enhance your existing WordPress site. You now have a platform for further experimentation with using Gatsby to power your site,



      Source link