gatsby_零部署:使用Gatsby.js(v1)的静态网站实用指南

gatsby

Since the advent of the modern web, performance has been a key consideration when designing a website or a web app. When a website requires no server interaction whatsoever, what is hosted on the web is served to a user as is, this is referred to as a static site.

自从现代网络问世以来,性能一直是设计网站或网络应用程序时的关键考虑因素。 如果网站不需要任何服务器交互,则将网络上托管的内容原样提供给用户,这称为静态站点。

In this post, we will simply be explaining the basics of Gatsby.js and build out a simple static blog in the process. The Blog will be deployed to the web using Netlify. Blog posts will be written in Markdown and GraphQL will be used to query markdown data into the blog. The final product will look like this:

在本文中,我们将仅解释Gatsby.js的基础知识,并在此过程中构建一个简单的静态博客。 该博客将使用Netlify部署到Web上。 博客帖子将用Markdown编写,而GraphQL将用于将markdown数据查询到博客中。 最终产品将如下所示:

什么是静态站点? ( What is a Static Site? )

A static site is a site which contains fixed content. In several use cases including event listings, portfolio pages and blogs, static sites are preferred to dynamic websites (requiring client-server interaction) because of challenges including slow load-time, security flaws, and hosting costs amongst others. The absence of a server mitigates these risks. Static Site Generators are tools used develop static sites, effectively and efficiently. Recently the use of static sites is on the rise and various tools and technologies such as Metalsmith, Jekyll, and Gatsby are taking center stage.

静态站点是包含固定内容的站点。 在包括事件列表,投资组合页面和博客在内的几种用例中,静态网站优于动态网站(需要客户端与服务器的交互),原因是加载速度慢,安全漏洞和托管成本等挑战。 没有服务器可以减轻这些风险。 静态站点生成器是用于有效且高效地开发静态站点的工具。 最近,静态站点的使用正在增加,诸如Metalsmith,Jekyll和Gatsby之类的各种工具和技术正在成为焦点。

Gatsby.js简介 ( Introducing Gatsby.js )

Gatsby is simply a robust and fast static site generator which uses React.js to render static content on the web. Content is written as React components and is rendered at build time to the DOM as static HTML, CSS and JavaScript files. By default, Gatsby builds a PWA. Like most static site generators, Gatsby requires plugins to either extend its functionality or modify existing functionality.

Gatsby只是一个强大而快速的静态站点生成器,它使用React.js在Web上呈现静态内容。 内容被编写为React组件,并在构建时以静态HTML,CSS和JavaScript文件的形式呈现给DOM。 默认情况下,Gatsby构建一个PWA。 与大多数静态网站生成器一样,Gatsby要求插件扩展其功能或修改现有功能。

Gatsby is said to be robust in a way that the static content rendered can be sourced from a large number of sources and formats including markdown, CSV and from CMS like Wordpress and Drupal. All that is required are plugins to handle the data transformation. Plugins in Gatsby are of three categories.

据称Gatsby具有强大的功能,可以从大量资源和格式(包括markdown,CSV和Wordpress和Drupal等CMS)中获取呈现的静态内容。 所需要的只是用于处理数据转换的插件。 Gatsby中的插件分为三类。

  • Functional Plugins: These plugins simply extend the ability of Gatsby. An example is the gatsby-plugin-react-helmet which allows the manipulation of the Head of our document.

    功能插件:这些插件只是扩展了盖茨比的功能。 一个例子是gatsby-plugin-react-helmet,它可以操纵文档的Head。
  • Source Plugins: This plugin ‘finds’ files in a Gatsby project and creates File Nodes for each of this files, these files can then be manipulated by transformer plugins. An example is the gatsby-source-filesystem which ‘sources’ files in the filesystem of a Gatsby project and creates File Nodes containing information about the file.

    源插件:该插件在Gatsby项目中“查找”文件,并为每个文件创建文件节点,然后可以由转换器插件操纵这些文件。 一个例子是gatsby-source-filesystem,它在Gatsby项目的文件系统中“获取”文件并创建包含有关文件信息的文件节点。
  • Transformer Plugins: Like we saw earlier, data in Gatsby can come from multiple sources and transformer plugins are responsible for converting these files to formats recognizable by Gatsby. An example is the gatsby-transformer-remark plugin which converts Markdown File Nodes from the filesystem into MarkdownRemark which can be utilized by Gatsby. Other plugins exist for various data sources and you can find them here.

    Prerequisites

    To build out this blog, knowledge of HTML, CSS, and JavaScript is required with a focus on ES6 Syntax and JavaScript Classes. Basic knowledge of React and GraphQL is also of advantage.

    Installation

    Since this is a node.js project, Node and its package manager NPM are required. Verify if they are installed on your machine by checking the current version of both tools with:

    变形金刚插件:就像我们之前看到的,盖茨比中的数据可以来自多个来源,而变形金刚插件负责将这些文件转换为盖茨比可以识别的格式。 一个示例是gatsby-transformer-remark插件,该插件将Markdown文件节点从文件系统转换为MarkdownRemark,Gatsby可以使用它。 存在用于各种数据源的其他插件,您可以在此处找到它们。

    先决条件

    要构建此博客,需要具备HTML,CSS和JavaScript知识,重点是ES6语法和JavaScript类。 React和GraphQL的基础知识也很有利。

    安装

    由于这是一个node.js项目,因此需要Node及其包管理器NPM。 通过使用以下方法检查两个工具的当前版本,验证它们是否已安装在您的计算机上:
node -v&& npm -v

Else, install Node from here.

否则,从这里安装Node。

Gatsby offers a powerful CLI tool for a faster build of static sites. The Gatsby CLI installs packages known as ‘starters’. These starters come as pre-packaged projects with essential files to speed up the development process of the static site. Install the Gatsby CLI with:

Gatsby提供了功能强大的CLI工具,可以更快地构建静态站点。 Gatsby CLI安装称为“启动程序”的软件包。 这些启动器是带有基本文件的预打包项目,可加快静态站点的开发过程。 使用以下命令安装Gatsby CLI:

npm install -g gatsby-cli

This installs the CLI tool, then proceed to create a new project with the Gatsby default starter.

这将安装CLI工具,然后使用Gatsby默认启动程序继续创建新项目。

gatsby new scotch-blog

This should take a while as the tool downloads the starter and runs npm install to install all dependencies.

该工具将下载启动程序并运行npm install来安装所有依赖项,这需要一段时间。

Once the installation is complete change directory to the project folder and start the development server with:

安装完成后,将目录更改为项目文件夹,并使用以下命令启动开发服务器:

cd scotch-blog && gatsby develop

This starts a local server on port 8000.

这将在端口8000上启动本地服务器。

The web page looks like:

该网页如下所示:

Gatsby’s default starter comes with all essential files we require for development. You can find other starters here and even create or contribute to a starter.

Gatsby的默认启动器随附了我们开发所需的所有基本文件。 您可以在此处找到其他入门者,甚至可以创建或贡献入门者。

For a simple blog all we require are:

对于一个简单的博客,我们需要的是:

  1. Have a blog homepage.

    有一个博客主页。
  2. Write blog posts in markdown.

    用markdown写博客文章。
  3. Display blog post titles on the homepage.

    在首页上显示博客文章标题。
  4. View each blog post on a separate page.

    在单独的页面上查看每个博客文章。

For these, we will require the three plugins we stated earlier to which will manipulate the <head /> element of our blog, source markdown files and transform markdown files respectively. All styling will be done via external CSS files and in-line component styling in React, however, several other methods of styling Gatsby documents exist such as CSS modules, typography.js, and CSS-in-JS. You can read more about them here.

对于这些,我们将需要我们前面提到的三个插件,分别用于操作博客的<head />元素,源markdown文件和transform markdown文件。 所有样式都将通过外部CSS文件和React中的嵌入式组件样式来完成,但是,存在多种其他样式Gatsby文档的方法,例如CSS模块,typography.js和CSS-in-JS。 您可以在此处阅读有关它们的更多信息。

Install required plugins with:

使用以下方法安装所需的插件:

npm install --save gatsby-transformer-remark gatsby-source-filesystem

Note: The gatsby-plugin-react-helmet comes preinstalled with the default Gatsby starter

注意:gatsby-plugin-react-helmet预先安装了默认的Gatsby启动器

Configure Plugins Before we go ahead to create pages, let’s configure the installed plugins. Navigate to gatsby-config.js in the root directory of your project and edit it to:

配置插件在继续创建页面之前,让我们配置已安装的插件。 导航到项目根目录中的gatsby-config.js并将其编辑为:

module.exports = {
  siteMetadata: {
    title: 'The Gray Web Blog',
  },
  plugins: [
    'gatsby-plugin-react-helmet',
    'gatsby-transformer-remark',
    {
      resolve: `gatsby-source-filesystem`,
      options:{
        name: `src`,
        path: `${__dirname}/src/`
      }
    },
  ],
};

Gatsby runs the gatsby-config.js during build and implements all installed plugins. One great thing about Gatsby is that it comes with a hot reload feature so changes made on the source files are immediately visible on the website rendered.

Gatsby在构建期间运行gatsby-config.js并实现所有已安装的插件。 Gatsby的一大优点是它具有热重载功能,因此对源文件所做的更改可以在呈现的网站上立即看到。

Note the siteMetadata in the gatsby-config module, this can be used to set the value of any element dynamically using GraphQL, for instance - document title and page title.

注意gatsby-config模块中的siteMetadata,它可以用于使用GraphQL动态设置任何元素的值,例如-文档标题和页面标题。

布局 ( Layout )

One key design feature considered during development is the layout of pages. This consist of any element we would like to be consistent across all pages. They include headers, footers, navbars e.t.c. For our blog, the default Gatsby starter provides a default layout which is found in src/layouts. To make some changes to the header, edit the index.js file in layouts. first import all required dependencies with:

开发过程中考虑的一项关键设计功能是页面的布局。 这包括我们希望在所有页面上保持一致的任何元素。 它们包括页眉,页脚,导航栏等。对于我们的博客,默认的Gatsby启动器提供了默认的布局,该布局可在src/layouts找到。 要对标题进行一些更改,请在布局中编辑index.js文件。 首先使用以下命令导入所有必需的依赖项:

import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import Header from '../components/Header'
import './index.css'

Note the imported CSS file. Gatsby supports the use of external stylesheets to style React components.

注意导入CSS文件。 Gatsby支持使用外部样式表来对React组件进行样式设置。

Edit the React component to:

编辑React组件以:

const TemplateWrapper = ({ children }) => (
  <div>
    <Helmet
      title="The Gray Web Blog"
      meta={[
        { name: 'description', content: 'Sample' },
        { 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

<Helmet/> is a component provided by the react-helmet plugin shipped originally with Gatsby’s default starter. A Header component is imported and the div to contain all page elements is styled in-line. Gatsby offers the flexibility of creating custom components in react and these components can as well be stateful or stateless. We will stick to using stateless components in this tutorial, like the <Header/> component.

<Helmet/>是由最初由Gatsby的默认启动程序提供的react-helmet插件提供的组件。 将导入一个Header组件,并且将包含所有页面元素的div设置为嵌入式样式。 Gatsby提供了在react中创建自定义组件的灵活性,这些组件也可以是有状态的或无状态的。 在本教程中,我们将坚持使用无状态组件,例如<Header/>组件。

Navigate to the header component in src/components/header/index.js edit it to:

导航到src/components/header/index.js的标头组件,将其编辑为:

const Header = () => (
  <div
    style={{
      background: 'black',
      marginBottom: '1.45rem',
      marginTop:'0px',
      display:'block',
      boxShadow:'0px 0px 7px black',
    }}
  >
    <div
      style={{
        margin: '0 auto',
        maxWidth: 960,
        padding: '1.45rem 1.0875rem',
      }}
    >
      <h1 style={{ margin: 0, textAlign:'center' }}>
        <Link
          to="/"
          style={{
            color: 'white',
            textDecoration: 'none',
          }}
        >
          The Gray Web Blog
        </Link>
      </h1>
    </div>
  </div>
)
export default Header

We simply made some changes to the styling by changing the background color of the header and aligning the header text to the center.

我们只需更改标题的背景颜色并将标题文本与中心对齐,即可对样式进行一些更改。

So far we have created the layout of the blog, how about we do some cool stuff by creating blog posts and displaying them on the home page.

到目前为止,我们已经创建了博客的布局,如何通过创建博客帖子并将其显示在主页上来做一些很酷的事情。

创建博客文章 ( Create Blog Posts )

Blog posts are created in markdown as earlier stated. In src, create a folder titled blog-posts. This will house all blog posts to be served. Create three sample markdown files with titles. We have:

如前所述,博客文章是在markdown中创建的。 在src ,创建一个名为blog-posts的文件夹。 这将容纳所有要发布的博客文章。 创建三个带有标题的示例降价文件。 我们有:

basic-web-development.md

基本网页开发

---
title: "Basic Web Development"
date: "2018-01-01"
author: "Chris Ashî"
---
Web development is a broad term for the work involved in developing a web site for the Internet (World Wide Web) or an intranet (a private network). Web development can range from developing the simplest static single page of plain text to the most complex web-based internet applications (or just 'web apps') electronic businesses, and social network services. A more comprehensive list of tasks to which web development commonly refers, may include web engineering, web design, web content development, client liaison, client-side/server-side scripting, web server and network security configuration, and e-commerce development.

in-the-beginning.md

在开始

---
title: "The Beginning of The Web"
date: "2018-01-10"
author: "Chuloo Will"
---
The World Wide Web ("WWW" or simply the "Web") is a global information medium which users can read and write via computers connected to the Internet. The term is often mistakenly used as a synonym for the Internet itself, but the Web is a service that operates over the Internet, just as e-mail also does. The history of the Internet dates back significantly further than that of the World Wide Web. - Wikipedia

and

vue-centered.md

以vue为中心

---
title: "Common Vue.js"
date: "2017-12-05"
author: "Alex Chî"
---
Vue.js (commonly referred to as Vue; pronounced /vjuː/, like view) is an open-source progressive JavaScript framework for building user interfaces.[4] Integration into projects that use other JavaScript libraries is made easy with Vue because it is designed to be incrementally adoptable. Vue can also function as a web application framework capable of powering advanced single-page applications. - Wikipedia

The texts between the triple dashes are known as frontmatter and provide basic information about the markdown post. We have our markdown post, to render this data, we would employ GraphQL.

三点划线之间的文本称为前题,提供有关降价桩的基本信息。 我们有markdown帖子,要呈现此数据,我们将使用GraphQL。

用GraphQL查询帖子 ( Querying Posts with GraphQL )

GraphQL is a powerful yet simple query language. Since its introduction, it is fast gaining popularity and has become a widely used means of consuming data in React. Gatsby ships with GraphQL by default. Since we have previously installed the gatsby-source-filesystem plugin, all files can be queried with GraphQL and are visible as File Nodes.

GraphQL是一种功能强大但简单的查询语言。 自引入以来,它Swift流行,并已成为在React中使用数据的一种广泛使用的方法。 默认情况下,Gatsby附带GraphQL。 由于我们先前已经安装了gatsby-source-filesystem插件,因此可以使用GraphQL查询所有文件,并且可以将其显示为文件节点。

GraphQL also comes with an important tool called GraphiQL an IDE with which we visualize and manipulate our data before passing it to React components. GraphiQL is available on http://localhost:8000/___graphql while the Gatsby server is running. Open up GraphiQL on that address to visualize data.

GraphQL还带有一个称为GraphiQL的重要工具,这是一个IDE,通过它我们可以在将数据传递给React组件之前对其进行可视化和操作。 当Gatsby服务器正在运行时,可以在http://localhost:8000/___graphql 。 在该地址上打开GraphiQL以可视化数据。

Run the query to see all files in /src/.

运行查询以查看/src/所有文件。

{
  allFile {
    edges {
      node {
        id
      }
    }
  }
}

This returns a list of all files in our src directory as we already specified that when configuring the gatsby-source-filesystem in the gatsby-config.js file. We have all the files in our source folder but we need only the markdown files and their accompanying data like frontmatter and size. The gatsby-transformer-remark plugin earlier installed comes in handy now.

如在gatsby-config.js文件中配置gatsby-source-filesystem时已经指定的那样,这将返回src目录中所有文件的列表。 我们将所有文件都保存在源文件夹中,但是我们只需要markdown文件及其随附的数据,例如frontmatter和size。 先前安装的gatsby-transformer-remark插件现在派上用场了。

The plugin transforms all markdown file nodes into MarkdownRemark nodes which can be queried for their content.

该插件将所有markdown文件节点转换为MarkdownRemark节点,可以查询其内容。

Run this query in GraphiQL to fetch all MarkdownRemark nodes and usable data in them.

在GraphiQL中运行此查询以获取所有MarkdownRemark节点和其中的可用数据。

{
  allMarkdownRemark {
    totalCount
    edges {
        node {
          frontmatter {
            title
            date
            author
          }
          excerpt
          timeToRead
        }
    }
  }
}

Running this query in GraphiQL will return a list of all markdown files and their corresponding data in a JSON object as requested. To pass this data to our page component, navigate to index.js in src/pages which holds the homepage. First, import all required dependencies as well as external stylesheets with:

在GraphiQL中运行此查询将根据请求在JSON对象中返回所有markdown文件及其对应数据的列表。 要将这些数据传递到我们的页面组件,请导航到保存主页的src/pages index.js。 首先,使用以下命令导入所有必需的依赖项以及外部样式表:

import React from 'react'
import Link from 'gatsby-link'
import './index.css'
...

Create and export an IndexPage stateless component and pass the data object to it as an argument:

创建和导出IndexPage无状态组件,并将数据对象作为参数传递给它:

const IndexPage = ({data}) => {
  console.log(data)
  return(
  <div>
    {data.allMarkdownRemark.edges.map(({node}) => (
      <div key={node.id} className="article-box">
        <h3 className="title">{node.frontmatter.title}</h3>
        <p className="author">{node.frontmatter.author}</p>
        <p className="date">{node.frontmatter.date} {node.timeToRead}min read</p>
        <p className="excerpt">{node.excerpt}</p>
      </div>
    ))}
  </div>
  )
}
export default IndexPage

The .map() method is used to traverse the data object for data to be passed to the components elements. We passed the title, author, date, time to read and excerpt to various JSX elements. We still haven’t queried this data. After the export statement create a GraphQL query with:

.map()方法用于遍历数据对象,以将数据传递给组件元素。 我们将标题,作者,日期,阅读时间和摘录传递给了各种JSX元素。 我们仍然没有查询此数据。 在export语句之后,创建带有以下内容的GraphQL查询:

export const  query = graphql`query HomePageQuery{
  allMarkdownRemark(sort: {fields: [frontmatter___date], order: DESC}) {
    totalCount
    edges {
      node {
        frontmatter {
          title
          date
          author
        }
        excerpt
        timeToRead
      }
    }
  }
}`

The sort query is used to sort articles by date in an ascending order so we have the earliest article on top. In src/pages/, create the CSS file imported with:

sort查询用于按日期升序对文章进行排序,因此我们将最早的文章放在顶部。 在src/pages/ ,创建通过以下方式导入CSS文件:

.article-box{
    margin-bottom: 1.5em;
    padding: 2em;
    box-shadow: 0px 0px 6px grey;
    font-family: 'Helvetica';
}
.title{
    font-size: 2em;
    color: grey;
    margin-bottom: 0px;
}
.author, .date{
    margin:0px;
}
.date{
    color: rgb(165, 164, 164);
}
.excerpt{
    margin-top: 0.6em; }

Restart the development server and we have:

重新启动开发服务器,我们有:

Alas, we have an awesome blog page with details and excerpt from the post content. We need to view each blog post on a separate page, let’s do that next.

las,我们有一个很棒的博客页面,其中包含文章内容的详细信息和摘录。 我们需要在单独的页面上查看每篇博客文章,接下来我们要做。

创建博客页面 ( Creating Blog Pages )

This is just about the best part of building out this blog, but also a bit complex. We could actually create individual pages in src/pages, pass the markdown content to the document body and link the pages to the blog titles but that would be grossly inefficient. We would be creating these pages automatically from any markdown post in src/blog-posts.

这仅是构建此博客的最佳部分,但也有些复杂。 实际上,我们可以在src/pages创建单个页面,将markdown内容传递到文档正文,然后将页面链接到博客标题,但是这样做效率极低。 我们将从src/blog-posts任何markdown帖子自动创建这些页面。

To accomplish this, we will require two important APIs which ship with Gatsby and they are:

为此,我们需要Gatsby随附的两个重要API,分别是:

  • onCreateNode

    onCreateNode
  • createPages

    createPages

We will simply be creating a ‘path’ otherwise known as ‘slug’ for each page and then creating the page itself from its slug. APIs in Gatsby are utilized by exporting a function from the Gatsby-node.js file in our root directory.

我们将简单地为每个页面创建一个“路径”(也称为“ slug”),然后根据其slug创建页面本身。 通过从根目录下的Gatsby-node.js文件导出函数来利用Gatsby中的API。

In Gatsby-node.js, export the onCreateNode function and create the file path from each File node with:

在Gatsby-node.js中,导出onCreateNode函数并使用以下命令从每个File节点创建文件路径:

const { createFilePath } = require(`gatsby-source-filesystem`)

exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {
  const { createNodeField } = boundActionCreators
  if (node.internal.type === `MarkdownRemark`) {
    const slug = createFilePath({ node, getNode, basePath: `pages` })
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}
...

The createFilePath function ships with the gatsby-source-filesystem and enables us to create a file path from the File nodes in our project. First, a conditional statement is used to filter only the markdown file nodes, while the createFilePath creates the slug for each File node. The createNodeField function from the API adds the slug as a field to each file node, in this case, Markdown File nodes. This new field created(slug) can then be queried with GraphQL.

createFilePath函数与gatsby-source-filesystem ,使我们能够从项目中的File节点创建文件路径。 首先,条件语句仅用于过滤降价文件节点,而createFilePath为每个File节点创建段。 API中的createNodeField函数将该段作为字段添加到每个文件节点(在本例中为Markdown File节点)。 然后可以使用GraphQL查询创建的这个新字段(段)。

While we have a path to our page, we don’t have the page yet. To create the pages, export the createPages API which returns a Promise on execution.

尽管我们有页面的路径,但我们还没有该页面。 要创建页面,请导出createPages API,该API在执行时返回Promise。

const path = require(`path`)
...
exports.createPages = ({ graphql, boundActionCreators }) => {
  const { createPage } = boundActionCreators
  return new Promise((resolve, reject) => {
    graphql(`{
        allMarkdownRemark {
          edges {
            node {
              fields {
                slug
              }
            }
          }
        }
      }`).then(result => {
      result.data.allMarkdownRemark.edges.forEach(({ node }) => {
        createPage({
          path: node.fields.slug,
          component: path.resolve(`./src/templates/posts.js`),
          context: {
            slug: node.fields.slug,
          },
        })
      })
      resolve()
    })
  })
}

In the createPages API, a promise is returned which fetches the slugs created using a GrphQL query and then resolves to create a page with each slug. The createPage method, creates a page with the specified path, component, and context. The path is the slug created, the component is the React component to be rendered and the context holds variables which will be available on the page if queried in GraphQL.

createPages API中,返回一个Promise,该Prom获取使用GrphQL查询创建的段,然后解析为每个段创建一个页面。 createPage方法创建具有指定路径,组件和上下文的页面。 路径是创建的段,组件是要渲染的React组件,上下文包含变量,如果在GraphQL中进行查询,该变量将在页面上可用。

创建博客模板 ( Creating The Blog Template )

To create the blog template, navigate to /src/ and create a folder called templates with a file named posts.js in it. In post.js, import all dependencies and export a functional component with:

要创建博客模板,请导航至/src/并创建一个名为template的文件夹,其中包含名为posts.js的文件。 在post.js中,导入所有依赖项并使用以下命令导出功能组件:

import React from "react";
export default ({ data }) => {
  const post = data.markdownRemark;
  return (
    <div>
      <h1>{post.frontmatter.title}</h1>
      <h4 style={{color: 'rgb(165, 164, 164)'}}>{post.frontmatter.author} <span style={{fontSize: '0.8em'}}> -{post.frontmatter.date}</span></h4>
      <div dangerouslySetInnerHTML = {{ __html: post.html }}/>
    </div>
  );
};

You can see GraphQL data already being consumed, query the data using GraphQL with:

您可以看到已经使用了GraphQL数据,并使用GraphQL查询数据:

export const query = graphql`query PostQuery($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      html
      frontmatter {
        title
        author
        date
      }
    }
  }`;

We have our blog pages and the content. Lastly, link the post titles in the homepage to their respective pages. In src/pages/index.js, edit the post title header to include the link to the post content:

我们有我们的博客页面和内容。 最后,将首页中的帖子标题链接到各自的页面。 在src/pages/index.js ,编辑帖子标题标题以包含指向帖子内容的链接:

...
<Link to={node.fields.slug} style={{textDecoration: 'none', color: 'inherit'}}><h3 className="title">{node.frontmatter.title}</h3></Link>
...

Since we require data on the slug, edit the GraphQL query to include the slug:

由于我们需要数据块中的数据,因此请编辑GraphQL查询以包括数据块:

export const  query = graphql`query HomePageQuery{
  allMarkdownRemark(sort: {fields: [frontmatter___date], order: DESC}) {
    totalCount
    edges {
      node {
        fields{
          slug
        }
        frontmatter {
          title
          date
          author
        }
        excerpt
        timeToRead
      }
    }
  }
}`

Yikes, our static blog is ready, restart the development server and we have:

Yikes,我们的静态博客已经准备好,重新启动开发服务器,我们有:

Running Gatsby build will create a production build of your site in the public directory with static HTML files and JavaScript bundles.

运行Gatsby build将在公共目录中使用静态HTML文件和JavaScript捆绑包创建网站的生产构建。

部署博客以进行Netlify ( Deploy Blog to Netlify )

So far we have built out a simple static blog with blog content and pages. It will be deployed using Netlify and Github for continuous deployment. Netlify offers a free tier which allows you deploy static sites on the web.

到目前为止,我们已经构建了一个包含博客内容和页面的简单静态博客。 它将使用Netlify和Github进行部署以进行连续部署。 Netlify提供了一个免费层,可让您在Web上部署静态站点。

Note: Pushing code to Github and deploying to Netlify from Github ensures that once a change is made to the repository on Github, the updated code is served by Netlify on build.

注意:将代码推送到Github并从Github部署到Netlify可以确保对Github上的存储库进行更改后,Netlify会在构建时提供更新的代码。

Create an account with Github and Netlify. In Github, create an empty repository and push all files from your project folder to the repository.

使用Github和Netlify创建一个帐户。 在Github中,创建一个空的存储库,并将所有文件从项目文件夹推送到存储库。

Netlify offers a login option with Github. Log into Netlify with your Github account or create a new account with Netlify. Click the ‘New site from Git’ button and select your Git provider.

Netlify提供了Github的登录选项。 使用您的Github帐户登录Netlify或使用Netlify创建一个新帐户。 点击“来自Git的新站点”按钮,然后选择您的Git提供商。

Github is the chosen Git Provider in this case.

在这种情况下,Github是选定的Git提供商。

Select Github and choose the repository you wish to deploy, in this case, the repository for the static blog. Next, specify the branch to deploy from, build command, and publish directory.

选择Github,然后选择要部署的存储库,在这种情况下,是静态博客的存储库。 接下来,指定要从中部署的分支,build命令和发布目录。

Click the ‘Deploy site’ Button to deploy the static site. This may take few minutes to deploy after which the static site is deployed to a Netlify sub-domain. Here is the demo of the static blog built earlier. https://vigilant-bhaskara-66ed6e.netlify.com/.

单击“部署站点”按钮以部署静态站点。 部署可能需要几分钟,然后才能将静态站点部署到Netlify子域。 这是先前构建的静态博客的演示。 https://vigilant-bhaskara-66ed6e.netlify.com/

结论 ( Conclusion )

In this post, you have been introduced to building a static site with Gatsby which utilizes React components to generate static content on build. Gatsby offers a robust approach to static site generation with the ability to parse data from various sources with the help of plugins. The static site was also deployed to the web using Netlify. Feel free to try out other amazing features of Gatsby including the various styling techniques as well. Comments and suggestions are welcome and you can make contributions to the source code here.

在本文中,向您介绍了使用Gatsby构建静态站点的方法,该站点利用React组件在构建时生成静态内容。 Gatsby提供了一种强大的静态网站生成方法,能够借助插件解析各种来源的数据。 静态站点也使用Netlify部署到了Web。 随时尝试Gatsby的其他惊人功能,包括各种样式技巧。 欢迎提出意见和建议,您可以在此处为源代码做出贡献。

翻译自: https://scotch.io/tutorials/zero-to-deploy-a-practical-guide-to-static-sites-with-gatsbyjs

gatsby

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值