如何建立你的第一个 Gatsby 网站

作者选择/dev/color接受捐赠,作为Write for DOnations计划的一部分。

介绍

Gatsby是一个React框架,允许您创建静态和无服务器应用程序。Gatsby 网站与传统网站不同,因为它们通常部署在内容交付网络 (CDN) 上并且与内容无关。从 CDN 部署的优势在于延迟更小,网站通常可以更快地提供给客户端。

Gatsby 通常被描述为内容网格内容网格意味着作为用户,您可以从各种来源(例如WordPress站点、CSV 文件和各种外部 API)提取数据因此,盖茨比是数据不可知论者。这与 WordPress 和Drupal等传统内容管理系统 (CMS) 不同,后者的数据通常来自单一来源——数据库。在 Gatsby 上构建应用程序时,您不必担心维护和配置数据库。此外,当您使用 Gatsby 时,您可以构建一个以速度和灵活性着称的框架。

这些无服务器网站也称为JAMStack在 JAMStack 架构中,仍然涉及服务器,但开发人员不需要提供或维护服务器。一些开发人员将无服务器视为一种理想的特性,因为他们可以将更多的注意力集中在应用程序的业务逻辑上。例如,如果他们正在创建电子商务商店,他们可以专注于与创建和销售产品直接相关的代码。JAMStack 可帮助开发人员快速开发比传统 CMS 框架更安全、性能更高且部署成本更低的网站。

在本教程中,您将:

  • 安装 Gatsby Starter 默认模板。
  • 修改gatsby config.
  • 运行开发服务器并在本地查看 Gatsby 站点。
  • 简要介绍 JSX 和 Gatsby 的图像优化功能。

在本教程结束时,您将能够创建和修改 Gatsby 站点。您将启动并运行您的第一个 Gatsby 电子商务网站。请记住,您将在本地计算机上创建此站点,并且不会部署它。

先决条件

步骤 1 — 安装 Gatsby 并创建新项目

在这一步中,您将从模板安装一个新的 Gatsby 站点。Gatsby 为用户提供了入门模板,因此您不必担心从零开始构建网站。

下载 Gatsby CLI 包。这个 Gatsby 命令行界面将允许您创建和自定义一个新站点:

  • npm install -g gatsby-cli

-g标志表示您正在全局而非本地安装 Gatsby 命令行界面。这将允许您在任何目录中使用该工具。

注意:在Ubuntu 18.04等一些系统上,全局安装npm包会导致权限错误,会导致安装中断。由于避免使用sudowith是一种安全最佳实践npm install,因此您可以通过更改 npm 的默认目录来解决此问题。如果遇到EACCES错误,请按照官方 npm 文档中说明进行操作

如果您键入,gatsby help您会发现几个可用于创建 Gatsby 站点的命令:

  • gatsby help

这将提供以下输出:

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. ...

以下是本教程最重要的命令:

  • gatsby new创建一个全新的站点。如果您gatsby new单独使用,您将获得一个准系统站点。更常见的使用方法gatsby new是将其与入门模板结合使用,这就是您将在本教程中执行的操作。

  • gatsby develop启动开发服务器。在本教程中,您将使用gatsby develop本地端口查看您的站点:8000

  • gatsby build 捆绑静态文件和资产并创建应用程序的生产版本。

您现在已经安装了 Gatsby 命令行工具,但您仍然没有站点。Gatsby 的优点之一是您不必从头开始编写网站代码。Gatsby 有几个入门模板,您可以使用它们来启动和运行您的网站。有数百个模板,其中许多贡献来自社区。在本教程中,您将使用 Gatsby 的官方入门模板之一,Gatsby Starter Default

您要做的第一件事是通过终端安装 Gatsby 启动器:

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

gatsby new创建一个新站点。本教程将使用gatsby-starter-default模板,并将模板命名项目。

命令行中的以下输出表示您已成功安装 Gatsby 入门模板:

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.

Step 2 — Modifying the Title, Description, and Author Metadata in Your Gatsby Config

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:

  • nano gatsby-config.js

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:

  • gatsby develop

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:

  • nano src/pages/index.js

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:

  • cd src/images

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

  • ls

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:

  • cd ..

Now open the image.js component:

  • nano components/image.js

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.

觉得文章有用?

点个广告表达一下你的爱意吧 !😁