gatsby_Gatsby.js:如何设置和使用React Static Site Generator

方通
2023-12-01

gatsby

Gatsby is a static site generator for React that released its first major version last month. It’s a tool that not only scaffolds projects (or websites) for you but claims that those sites are fast in performance. If you decide to use Gatsby you will be enjoying the power of the latest web technologies such as React.js, Webpack, and so on.

Gatsby是React的静态站点生成器,上个月发布了其第一个主要版本。 该工具不仅可以为您搭建项目(或网站),还可以声称这些网站的性能很快。 如果您决定使用Gatsby,您将享受最新Web技术的强大功能,例如React.js,Webpack等。

There are a lot of modern paradigms that Gatsby takes care for its developer behind the scenes to start building and launch their project. Another cool thing about Gatsby that I like is its ever-growing data plugin ecosystem. It lets a developer fetch data directly into a Gatsby generated application using GraphQL.

盖茨比在后台照顾着许多开发人员,以开始构建和启动他们的项目,这有很多现代范式。 我喜欢盖茨比的另一个很棒的地方是它不断增长的数据插件生态系统。 它使开发人员可以使用GraphQL将数据直接提取到Gatsby生成的应用程序中。

Here are some of the advantages of using Gatsby:

使用Gatsby的一些优点如下:

  • HTML code is generated server side

    服务器端生成HTML代码
  • Easily extensible by plugin ecosystem

    插件生态系统可轻松扩展
  • Pre-configured Webpack based build system (no need to break your head)

    预先配置的基于Webpack的构建系统(无需费神)
  • Optimized for speed. Gatsby loads only critical parts, so that your site loads as fast as possible. Once loaded, Gatsby prefetches resources for other pages so that clicking on the site feels incredibly fast.

    优化速度。 Gatsby仅加载关键部分,因此您的站点将尽快加载。 加载后,Gatsby会预取其他页面的资源,从而使您在网站上的点击速度非常快。
  • Automatic routing based on your directory structure. (no need for separate routing/navigation library)

    根据您的目录结构自动路由。 (无需单独的路由/导航库)

If you know the nitty-gritty of React, you can definitely get started with Gatsbyjs in no time by reading this tutorial. I am not asking you to be advanced with React but only the familiar with its concepts. If you like to refresh your knowledge on the same or learn more about it, I recommend following links:

如果您了解React的精髓,那么一定可以通过阅读本教程立即开始使用Gatsbyjs。 我并不是要让您对React有所了解,而只是要求您熟悉它的概念。 如果您想通过相同的方式刷新知识或了解更多信息,建议您使用以下链接:

Enough with the introduction. Let’s get started.

足够介绍。 让我们开始吧。

安装Gatsby CLI (Installing Gatsby CLI)

We will be using npm to install our first and basic tool that we need to setup any Gatsby project. You can use yarn too. In your terminal, please execute this command:

我们将使用npm安装第一个基本工具,这是设置任何Gatsby项目所需的工具。 您也可以使用yarn 。 在您的终端中,请执行以下命令:

npm install --global gatsby-cli

You might need to add sudo at the start of the command if it gives an error for permissions.

如果命令权限错误,则可能需要在sudo开头添加sudo

To start a new site, go to your desired project directly. Select a place on your system where you might be storing all the playground or applications in their initial stage and then in terminal:

要启动新站点,请直接转到所需的项目。 在系统上选择一个地方,您可以在它们最初存储所有游乐场或应用程序的地方,然后在终端中:

gatsby new first-gatsby-site

You can name your project anything you like, I named that just for the brevity.

您可以根据自己的喜好命名项目,为简便起见,我将其命名为。

Finish the installation and set up of the project. Then change the directory into the newly created folder. Run gatsby develop from the command line to see your site running live at http://localhost:8000.

完成安装并设置项目。 然后将目录更改为新创建的文件夹。 gatsby develop运行gatsby develop ,以查看您的网站在http:// localhost:8000上实时运行。

In your browser window, the default Gatsby.js application looks like this:

在浏览器窗口中,默认的Gatsby.js应用程序如下所示:

Leave the command running since it enables Hot Reloading. Now any change we make to our project will be reflected directly, without refreshing the page.

使命令保持运行状态,因为它启用了热重装。 现在,我们对项目所做的任何更改都将直接反映出来,而无需刷新页面。

Currently, our application contains two pages. Hence, the bare minimum routing is already done for us. Before diving into the code and making any amendments to it, we need to understand the project structure. Then you can make use of it by manipulating it in your future projects.

当前,我们的应用程序包含两个页面。 因此,最低限度的路由已经为我们完成。 在深入研究代码并对其进行任何修改之前,我们需要了解项目结构。 然后,您可以通过在以后的项目中进行操作来使用它。

深入研究项目结构 (Diving deep in the Project Structure)

Every Gatsby project contains at least these files. You might be familiar with some such as node_modules, public directory, which is served when deployed. It also contains package.json, which contains the metadata of any modern Javascript application.

每个Gatsby项目至少包含这些文件。 您可能熟悉诸如node_modules, public目录之类的内容,它们在部署时会提供服务。 它还包含package.json,其中包含任何现代Javascript应用程序的元数据。

Our main focus and concern are in the directory src and file gatsby-config.js.These contain the metadata and other essential information about our current application.

我们的主要关注点是目录src和文件gatsby-config.js. 这些包含有关我们当前应用程序的元数据和其他基本信息。

Inside the src/ there are two sub-directories: layouts/ and pages/.

src/内部,有两个子目录: layouts/pages/

The layouts/ contain further two files: index.css and index.js. These serve as the starting point of our application.

layouts/包含另外两个文件: index.cssindex.js 。 这些是我们应用程序的起点。

import React from "react";
import PropTypes from "prop-types";
import Link from "gatsby-link";
import Helmet from "react-helmet";

import "./index.css";

const Header = () => (
  <div
    style={{
      background: "rebeccapurple",
      marginBottom: "1.45rem"
    }}
  >
    <div
      style={{
        margin: "0 auto",
        maxWidth: 960,
        padding: "1.45rem 1.0875rem"
      }}
    >
      <h1 style={{ margin: 0 }}>
        <Link
          to="/"
          style={{
            color: "white",
            textDecoration: "none"
          }}
        >
          Gatsby
        </Link>
      </h1>
    </div>
  </div>
);

const TemplateWrapper = ({ children }) => (
  <div>
    <Helmet
      title="My First Gatsby Site"
      meta={[
        { name: "author", content: "amanhimself" },
        { name: "keywords", content: "sample, something" }
      ]}
    />
    <Header />
    <div
      style={{
        margin: "0 auto",
        maxWidth: 960,
        padding: "0px 1.0875rem 1.45rem",
        paddingTop: 0
      }}
    >
      {children()}
    </div>
  </div>
);

TemplateWrapper.propTypes = {
  children: PropTypes.func
};

export default TemplateWrapper;

The Header component contains the styles and markup that is currently serving as the header of our application. It is reflected on every page by TempplateWrapper which is our main layout component in the application. This certainly means that this component can be used for displaying navigation menu (which we are going to do in a while) or a footer.

Header组件包含当前用作我们应用程序标头的样式和标记。 TempplateWrapper反映在每个页面上,这是我们在应用程序中的主要布局组件。 当然,这意味着该组件可用于显示导航菜单(我们将在一段时间内进行此操作)或页脚。

The Link tag you are seeing is the way Gatsby let our visitors navigate from one page to another. The react-helmet library that serves the purpose of attaching header information in HTML. It is being currently generated by the JSX. You can read about this useful, beginner friendly library on its official doc here.

您所看到的Link标签是Gatsby让访问者从一个页面导航到另一页面的方式。 react-helmet库用于在HTML中附加标头信息。 当前由JSX生成。 您可以在其官方文档中阅读有关此有用的,对初学者友好的库。

Do notice the {children()} prop. This is a function that executes within the JSX code to determine the exact location for the child components to render.

请注意{children()}道具。 该函数在JSX代码中执行,以确定要呈现的子组件的确切位置。

主要应用页面 (Main Application Page)

Our second concerned directory pages/ contain rest of the pages that build up our application. They are plain React components. Let's take a look at the index.js file inside this directory which currently serves as the main page of our application.

我们关注的第二个目录pages/包含构建应用程序的其余页面。 它们是普通的React组件。 让我们看一下该目录内的index.js文件,该文件当前用作应用程序的主页。

import React from "react";
import Link from "gatsby-link";

const IndexPage = () => (
  <div>
    <h1>Hi people</h1>
    <p>Welcome to your new Gatsby site.</p>
    <p>Now go build something great.</p>
    <Link to="/page-2/">Go to page 2</Link>
  </div>
);

export default IndexPage;

Similarly, you will find the code in page-2.js. If in our browser window, we try to navigate to the second page, notice the URL of the site when the second page loads.

同样,您可以在page-2.js找到代码。 如果在浏览器窗口中,我们尝试导航到第二页,请在第二页加载时注意站点的URL。

It is same as the file name. We are also using Link tag from Gatsby to navigate back to the homepage.

与文件名相同。 我们还使用Gatsby中的Link标记导航回主页。

Let’s add another page to our site. Inside the pages directory, create a new file page-3.js.

让我们向我们的网站添加另一个页面。 在pages目录内,创建一个新文件page-3.js

import React from "react";
import Link from "gatsby-link";

const ThridPage = () => (
  <div>
    <h1>Third Page</h1>
    <p>This is my first Gtasby site</p>
    <Link to="/page-2/">Back to Page 2</Link>
    <br />
    <Link to="/">Go back to the homepage</Link>
  </div>
);

export default ThridPage;

Now let’s add the link to our new page to the homepage. Open index.js file:

现在,让我们将指向新页面的链接添加到主页。 打开index.js文件:

import React from "react";
import Link from "gatsby-link";

const IndexPage = () => (
  <div>
    <h1>Hi people</h1>
    <p>Welcome to your new Gatsby site.</p>
    <p>Now go build something great.</p>
    <Link to="/page-2/">Go to page 2</Link>
    <br />
    <Link to="/page-3">New Page!</Link>
  </div>
);

export default IndexPage;

This renders correctly on our page. Do notice the 404.js file in the directory. This file is rendered when no desired URL is found. More info can be read in official Gatsby docs.

这可以在我们的页面上正确呈现。 请注意目录中的404.js文件。 找不到所需的URL时将呈现此文件。 有关更多信息,请参阅Gatsby官方文档

Now to make things a bit more interesting. Let’s add a navigation menu in the Header component of our layout.

现在让事情变得更有趣。 让我们在布局的Header组件中添加一个导航菜单。

添加导航菜单 (Adding Navigation Menu)

Open layouts/index.js and inside the Header component, add the following code:

打开layouts/index.js并在Header组件内,添加以下代码:

const Header = () => (
  <div
    style={{
      background: "rebeccapurple",
      marginBottom: "1.45rem"
    }}
  >
    <div
      style={{
        margin: "0 auto",
        maxWidth: 960,
        padding: "1.45rem 1.0875rem"
      }}
    >
      <h1 style={{ margin: 0 }}>
        <Link
          to="/"
          style={{
            color: "white",
            textDecoration: "none"
          }}
        >
          Gatsby
        </Link>
        <ul style={{ listStyle: "none", float: "right" }}>
          <li style={{ display: "inline-block", marginRight: "1rem" }}>
            <Link
              style={{
                color: "white",
                textDecoration: "none",
                fontSize: "x-large"
              }}
              to="/"
            >
              Home
            </Link>
          </li>
          <li style={{ display: "inline-block", marginRight: "1rem" }}>
            <Link
              style={{
                color: "white",
                textDecoration: "none",
                fontSize: "x-large"
              }}
              to="/page-2"
            >
              Page 2
            </Link>
          </li>
          <li style={{ display: "inline-block", marginRight: "1rem" }}>
            <Link
              style={{
                color: "white",
                textDecoration: "none",
                fontSize: "x-large"
              }}
              to="/page-3"
            >
              Page 3
            </Link>
          </li>
        </ul>
      </h1>
    </div>
  </div>
);

If you save the file, the results are reflected immediately on the homepage and on every page.

如果保存文件,结果将立即反映在主页和每个页面上。

配置文件 (Configuration File)

https://gist.github.com/dfbefb5a09c93f1816198d9db253dd6c

https://gist.github.com/dfbefb5a09c93f1816198d9db253dd6c

The last important file of our concern is gatsby-config.js in the root folder. This file can contain site's metadata and additional information such plugins that we install using npm command. However, their scope of usage and concern are only with a project generated using Gatsby CLI. By default the plugin gatsby-plugin-react-helmet is installed.

我们关注的最后一个重要文件是根文件夹中的gatsby-config.js 。 该文件可以包含网站的元数据和其他信息,例如我们使用npm命令安装的插件。 但是,它们的使用和关注范围仅与使用Gatsby CLI生成的项目有关。 默认情况下,已安装插件gatsby-plugin-react-helmet

A complete list of plugins is listed here.

此处列出了插件的完整列表。

部署我们的静态站点 (Deployment of our Static site)

So far we have come out with a bare minimum static site that serves the purpose of this walk-through. The last step that I want to focus is on deployment. I will be using GitHub Pages for deployment.

到目前为止,我们已经推出了一个最小的静态站点,可以满足本演练的目的。 我要重点关注的最后一步是部署。 我将使用GitHub Pages进行部署。

To deploy a project on GitHub pages make sure your current working directory is initialized as a git repository and hosted on GitHub. If that is good, let us add a module called gh-pages as a dev dependency.

要在GitHub页面上部署项目,请确保将当前工作目录初始化为git存储库并托管在GitHub上。 如果那很好,让我们添加一个名为gh-pages的模块作为dev依赖项。

npm install --save-dev gh-pages

Add a deployment script in package.json:

package.json添加部署脚本:

"scripts": {
  "deploy": "gatsby build --prefix-paths && gh-pages -d public",
}

In gatsby.config.js add the pathname prefix of the repo such:

gatsby.config.js添加gatsby.config.js的路径名前缀,例如:

module.exports = {
  siteMetadata: {
    title: `Gatsby Default Starter`
  },
  pathPrefix: `/first-gatsby-site`,
  plugins: [`gatsby-plugin-react-helmet`]
};

See official docs on path prefixing.

请参阅有关路径前缀的官方文档

Now from your terminal run:

现在从您的终端运行:

npm run deploy

Great! Your site is now live on https://username.github.io/project-name/.

大! 您的网站现在位于https://username.github.io/project-name/

You can find the complete code of this project at this GitHub Repo

您可以在GitHub Repo上找到该项目的完整代码

For more questions, contact me on Twitter, or read more about me at my website.

如有其他问题,请在Twitter上与我联系,或在我的网站上阅读有关我的更多信息。

翻译自: https://www.freecodecamp.org/news/setting-up-and-getting-used-to-gatsby-1fc27985ae8a/

gatsby

 类似资料: