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

来自菜鸟教程
跳转至:导航、​搜索

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

介绍

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

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

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

在本教程中,您将:

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

在本教程结束时,您将能够创建和修改 Gatsby 站点。 请记住,您将在本地计算机上创建此站点,而不会部署它。

先决条件

  • Node.js 版本 14(或更高版本)安装在您的计算机上。 要在 macOS 或 Ubuntu 20.04 上安装它,请按照 如何在 macOS 上安装 Node.js 和创建本地开发环境中的步骤或 使用 NodeSource PPA 使用 Apt 安装 Node.js [X207X ] 如何在 Ubuntu 20.04 上安装 Node.js 部分。
  • 这将有助于熟悉 使用 HTML 构建网站和使用 CSS 进行样式设置,您可以在 如何使用 CSS 设置 HTML 样式系列 中了解更多信息。
  • 了解 JavaScript 将很有用。 您可以在我们的 如何在 JavaScript 中编码系列 中了解有关 JavaScript 的更多信息。 虽然 Gatsby 使用 React,但您无需了解 React 即可开始使用,但熟悉基本概念会有所帮助。 你可以通过这个系列how-to-code-in-react-js学习React。

第 1 步 — 安装 Gatsby 并创建一个新项目

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

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

npm install -g gatsby-cli

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

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


如果你输入 gatsby help 你会发现几个命令可以用来创建你的 Gatsby 站点:

gatsby help

这将给出以下输出:

OutputUsage: 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.com/docs/gatsby-repl/)
  gatsby recipes [recipe]             [EXPERIMENTAL] Run a recipe
  gatsby plugin <cmd> [plugins...]    Useful commands relating to Gatsby plugins
  gatsby new [rootPath] [starter]     Create new Gatsby project.
  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. Start developing it by running:

  cd gatsby-starter-default
  gatsby develop

gatsby-starter-default 是新目录的名称。 您现在将更改为 gatsby-starter-default 并列出目录的内容:

cd gatsby-starter-default && ls

这将给出以下输出:

OutputLICENSE    gatsby-browser.js  gatsby-node.js  node_modules       package.json
README.md  gatsby-config.js   gatsby-ssr.js   package-lock.json  src

您将在本教程中修改的重要文件包括:

  • gatsby-config.js:这包含您的站点范围的自定义。 在这里您将修改元数据并添加 Gatsby 插件
  • src:此目录包含构成网站的所有页面、图像和组件。 在 React 中, 组件 是网站的独立部分。 例如,在您的网站中,index 页面由 layoutimageseo 组件组成。

现在您已经创建了一个新的 Gatsby 项目并探索了文件结构,您可以进入您的项目并自定义您的站点的元数据。

第 2 步 — 修改 Gatsby 配置中的标题、描述和作者元数据

如果您想让搜索引擎发现您的网站,正确格式化元数据非常重要。 在本节中,您将在应用程序中配置标题、描述和作者元数据。

gatsby-config.js 是 Gatsby 的配置文件。 在这里您可以找到站点 siteMetadata 对象。 网站元数据有助于提升您网站的 SEO 并使其更容易被搜索引擎发现。

在文本编辑器中打开 gatsby-config.js 以查看 Gatsby 的配置。 nano 是本教程将用于查看 Gatsby 配置文件的文本编辑器的名称,但您可以使用您选择的编辑器:

nano gatsby-config.js

以下是 gatsby-config.js 以及 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`,
    siteUrl: `https://gatsbystarterdefaultsource.gatsbyjs.io/`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-image`,
    {
      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`,
        // This will impact how browsers show your PWA/website
        // https://css-tricks.com/meta-theme-color-and-trickery/
        // 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`,
  ],
}

Gatsby 配置文件也是您的插件的所在地。 Plugins 是您安装的软件包,用于向 Gatsby 应用程序添加功能。 此 Gatsby 安装附带 gatsby-plugin-react-helmetgatsby-plugin-imagegatsby-transformer-sharpgatsby- plugin-sharpgatsby-plugin-manifest 插件。

每个 Gatsby Default Starter 模板都包含相同的通用元数据,这些元数据通过 gatsby-plugin-react-helmet 插件嵌入到您网站的每个页面中。 您将个性化这些数据,并开始将这个网站变成您自己的网站。

titledescriptionauthor 的文本替换为以下突出显示的代码:

盖茨比-config.js

module.exports = {
  siteMetadata: {
    title: `Getting Started with Gatsby`,
    description: `A tutorial that goes over Gatsby development`,
    author: `@digitalocean`,
    siteUrl: `https://gatsbystarterdefaultsource.gatsbyjs.io/`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-image`,
    {
      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`,
        // This will impact how browsers show your PWA/website
        // https://css-tricks.com/meta-theme-color-and-trickery/
        // 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`,
  ],
}

保存并退出文件。

现在,当 Google 或其他搜索引擎抓取您的网站时,它会检索与您的应用相关的数据。 您已更改元数据; 接下来,您将更改网站的其中一个页面。

第三步——修改索引页面

在本节中,您将了解 JSX、更改 index 页面上的标记、添加图像并在本地运行 Gatsby 站点。

是时候在浏览器中查看 Gatsby 网站的外观了。 在终端打开一个新窗口,在命令行输入gatsby develop查看网站本地版本:

gatsby develop

gatsby develop 命令启动开发服务器。 如果您转到浏览器,您可以通过 localhost:8000 访问您的站点:

您将更改页面上的标记,使其看起来更像您在电子商务网站上找到的内容。 在文本编辑器中打开 index 页面:

nano src/pages/index.js

这是您将在文本编辑器中找到的内容:

src/pages/index.js

import * as React from "react"
import { Link } from "gatsby"
import { StaticImage } from "gatsby-plugin-image"

import Layout from "../components/layout"
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>
    <StaticImage
      src="../images/gatsby-astronaut.png"
      width={300}
      quality={95}
      formats={["auto", "webp", "avif"]}
      alt="A Gatsby astronaut"
      style={{ marginBottom: `1.45rem` }}
    />
    <p>
      <Link to="/page-2/">Go to page 2</Link> <br />
      <Link to="/using-typescript/">Go to "Using TypeScript"</Link>
      <Link to="/using-ssr">Go to "Using SSR"</Link> <br />
      <Link to="/using-dsg">Go to "Using DSG"</Link>
    </p>
  </Layout>
)

export default IndexPage

这里的代码是 JSX。 JSX 允许您在 JavaScript 中编写 HTML 元素。 如果你想更全面地了解 JSX, 转到我们的 JSX 教程

在文本编辑器中,将 <h1>Hi People</h1> 替换为 <h1>Hello Shoppers, we are open for business!</h1>,将 <p>Welcome to your new Gatsby site.</p> 替换为 <p>We sell fresh fruit.</p>。 删除<p>Now go build something great.</p>

src/pages/index.js

import * as React from "react"
import { Link } from "gatsby"
import { StaticImage } from "gatsby-plugin-image"

import Layout from "../components/layout"
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>
    <StaticImage
      src="../images/gatsby-astronaut.png"
      width={300}
      quality={95}
      formats={["auto", "webp", "avif"]}
      alt="A Gatsby astronaut"
      style={{ marginBottom: `1.45rem` }}
    />
    <p>
      <Link to="/page-2/">Go to page 2</Link> <br />
      <Link to="/using-typescript/">Go to "Using TypeScript"</Link>
      <Link to="/using-ssr">Go to "Using SSR"</Link> <br />
      <Link to="/using-dsg">Go to "Using DSG"</Link>
    </p>
  </Layout>
)

export default IndexPage

保存您的更改。 无需启动和停止开发服务器,因为 Gatsby 自带 热重载 。 热重新加载会刷新应用中您已更改的文件:

您现在要将图像从 Gatsby 宇航员更改为 Sammy the Shark。 在浏览器中打开图像并将图像下载到 Gatsby 项目中的 src/images 文件夹。 将图像另存为 sammy-shark.jpeg。 或者,您可以从终端完成此步骤,方法是从 Gatsby 项目的根目录运行以下命令:

wget -O src/images/sammy-shark.jpeg https://html.sammy-codes.com/images/small-profile.jpeg

仔细检查以查看 Sammy the Shark 图像是否在正确的文件夹中。 导航到 images 文件夹:

cd src/images

进入 images 目录后,检查 sammy-shark.jpeg 是否在 images 文件夹中:

ls

ls 是列表命令。 您列出了在 images 文件夹中找到的所有文件:

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

现在您已确认该文件存在,您将在您喜欢的文本编辑器中重新打开 index.js。 您即将用 Sammy the Shark 替换 Gatsby 宇航员图像。

首先,返回您的 src 目录:

cd ..

现在打开 index.js React 组件页面:

nano pages/index.js

gatsby-astronaut.png 替换为 sammy-shark.jpeg

src/pages/index.js

import * as React from "react"
import { Link } from "gatsby"
import { StaticImage } from "gatsby-plugin-image"

import Layout from "../components/layout"
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>
    <StaticImage
      src="../images/sammy-shark.jpeg"
      width={300}
      quality={95}
      formats={["auto", "webp", "avif"]}
      alt="Sammy the Shark, an adorable cartoon shark and DigitalOcean's mascot"
      style={{ marginBottom: `1.45rem` }}
    />
    <p>
      <Link to="/page-2/">Go to page 2</Link> <br />
      <Link to="/using-typescript/">Go to "Using TypeScript"</Link>
    </p>
  </Layout>
)

export default IndexPage

在上面的页面代码中,您已经从 gatsby-plugin-image 更新了 StaticImage 组件,以加载和渲染 Sammy the Shark 图像,而不是 astronaut。 您已更新 src 属性以指向新图像文件的本地路径,并更新了 alt 文本属性,以便屏幕阅读器软件可以向用户读取新图像的有用描述那需要它。 描述性替代文本是 HTML 中图像可访问性的重要组成部分。

使用 StaticImage 的其他现有设置,Gatsby 将 sammy-shark.jpeg 的图像大小缩放到 300 的最大宽度,使用 95 的质量设置,生成多种格式以优化交付,并通过一些内联 CSS 添加底部边距。 您可以在 Gatsby 文档 中阅读有关 Gatsby 如何格式化图像的更多信息。

保存文件。 服务器将重新启动,您将在 Gatsby 页面上找到 Sammy the Shark:

您现在已经在本地启动并运行了 Gatsby 电子商务网站。

结论

在本教程中,您创建了您的第一个 Gatsby 网站。 你已经学会了如何在你的本地机器上建立一个基本的 Gatsby 站点。 现在您可以创建和自定义 Gatsby 应用程序,下一步是 部署您的 Gatsby 电子商务网站