First post my new blog address ==> new.ruodan.cn /

The old

origin

I used to use hexo, and here’s why we started from Hexo ==> Gatsby:

  1. Are static page frameworks, SEO, deployment, etc., advantages of static pages
  2. React is developed with a modern framework that allows constant iteration
  3. The community resources are mature. At present, the Plug-ins of Gatsby are very mature and linked
  4. Powerful performance. Compared with other static page frameworks, Gatsby has superior performance
  5. To request data, GraphQL is flexible and elegant

install

Initialize scaffolding by installing the global Gastby command line. yarn global add gastby-cli

script

  • develop
  • build
  • serve

Structure-normal form

├─ Content ├─ Gatsby - browse.js // Main Config File ├─ Gatsby -node.js // View Layer Config ├─ package.json ├─ public ├─ SRC ├─ Components // Component ├─ pages // Page File ├─ Templates //Copy the code

Gatsby uses contracted routing. Note that the page folder is all named in lowercase, for example:

about.js ==> http://localhost/about/

In addition, the createPage can set routes manually during production pages, but it is recommended that you follow the convention

Data

For the data layer, Gatsby used Graphql, documents

Gatsby comes with an image debugging interface

http://localhost:8000/___graphql

🔥 lace such an interface, later explained his simple use

⚠️ Note: you can use the Query parameter on the right, which is a convenient batch of ~

Data in Gatsby are divided into two types

  1. The file data
  2. The configuration data

Through plug-ins

gatsby-source-filesystemRead the list of local files,

query {
   allFile {
      edges {
        node {
          relativePath
          prettySize
          extension
          birthTime(fromNow: true)}}}Copy the code

Read the markdown file content through gatsby- Transformer -remark

const result = await graphql(
    ` { allMarkdownRemark( sort: { fields: [frontmatter___date], order: DESC } limit: Edges {node {fields {slug} frontmatter {date(formatString: "YYYY year MM month DD date ") title tags}}}}} '
  )
Copy the code

Note that my graphQL is slightly different. When I get the markdown, I sort it in reverse order by date, and format the time as follows: It can do a lot more than that with parameters like sort, filter, skip, and limit. See the documentation for details

All the data in Gatsby were realized through promises, such as the content of the above Markdown file

Then (res => {… })

Here’s how to get the configuration data that is gatsby-config.js

query {
    site {
      siteMetadata {
        title
      }
    }
Copy the code

My configuration file is structured like 👇

    module.exports = {
  siteMetadata: {
    title: `Ruoduan'Blog', Author: 'Ruoduan', Description: 'My introduction... `, siteUrl: `https://github.com/Chad97`, keywords: 'React, front-end, Python, JS,',},}, plugins: [Installed plug-in configuration......] ,}Copy the code

See at a glance ~ ~

Black magic

To get the data on the Gatsby Page, go to 👇

export const pageQuery = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC },
      ) {
      edges {
        node {
          excerpt
          fields {
            slug
          }
          frontmatter {
            date(formatString: "YYYY year MM month DD day")
            title
            tags
            categories
          }
        }
      }
    }
  }
`
Copy the code

You just need to export a graphQL to get the data and it will mount to the props on the current page

useStaticQuery

What if we want to get some data in the component other than the way above?

Gatsby has a very elegant way ———— useStaticQuery

Unlike useStaticQuery, where the data is only available in the runtime of the current component,

For example, in the following component I want to get all the article titles

import { useStaticQuery, graphql } from "gatsby"
const data = useStaticQuery(graphql` query titleQuery { allMarkdownRemark { edges { node { frontmatter { title } } } } } `)
  
  const[titleData, setTitle] = useState (data) allMarkdownRemark) edges) useStaticQuery must start on components, namely data variable beforeCopy the code

👏 👏 👏

createPages

We were faced with duplicate pages such as blog post details, but the data was different. We could not create a page for every markdown, so we needed to createPages using createPages

createPage({
      path: post.node.fields.slug,
      component: blogPost,
      context: {
        slug: post.node.fields.slug,
        previous,
        next,
      },
Copy the code

Three parameters:

  • Path: routing address, I used the article title here

  • Component: template

  • Context: Data passed to the page

I created the page here by using all the markdown data retrieved above to create the article details page

    const result = await graphql(
    ` { allMarkdownRemark( ...... As above} `
  )
  // Get the MD data
const posts = result.data.allMarkdownRemark.edges

const blogPost = path.resolve(`./src/templates/blog-post.js`)
  // Create a detail page
  posts.forEach((post, index) = > {
    const previous = index === posts.length - 1 ? null : posts[index + 1].node
    const next = index === 0 ? null : posts[index - 1].node

    createPage({
      path: post.node.fields.slug,
      component: blogPost, 
      context: {
        slug: post.node.fields.slug,
        previous,
        next,
      },
    })
  })
Copy the code

Develop Tools

  • babel

.babelrc, and Gatsby installed Babel-Preth-Gatsby, which is not much different from us except for the preset package

  • webpack

Webpack wants to customize the configuration

gatsby-node.js

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) = > {
  if (stage === "build-html") {
    actions.setWebpackConfig({
      module: {
        rules: [...] ,},})}}Copy the code

Stage is divided into:

  • develop
  • develop-html
  • build-javascript
  • build-html

Other

PWA support

yarn add gatsby-plugin-manifest gatsby-plugin-offline

plugins: [
  / /...
  {
    resolve: `gatsby-plugin-manifest`.options: {
      name: `Destiny'Note`.short_name: `Destiny`.start_url: ` / `.background_color: `#6b37bf`.theme_color: `#6b37bf`.display: `standalone`.icon: `src/images/icon.png`,}},`gatsby-plugin-offline` // This plug-in must be after the manifest
]
Copy the code

proxy

Two ways,

  1. There is a proxy in gatsby-config.js, similar to umi or webpack-dev-server
  2. Gatsby – Node. js comes with developMiddleware, handwriting middleware

SEO

yarn add gatsby-plugin-react-helmet react-helmet

{
  siteMetadata: {
    // These three attributes are mandatory
    title: `Destiny'Note`.author: `destiny`.description: `my own blog`.keywords: `react, graphql, gatsby`
  },
  plugins: [
    / /...
    `gatsby-plugin-react-helmet`]}Copy the code

Add seo.js file under SRC /components:

/** * SEO component that queries for data with * Gatsby's useStaticQuery React hook * * See: https://www.gatsbyjs.org/docs/use-static-query/ */

import React from "react"
import PropTypes from "prop-types"
import Helmet from "react-helmet"
import { useStaticQuery, graphql } from "gatsby"

function SEO({ description, lang, meta, title, tags }) {
  const { site } = useStaticQuery(
    graphql` query { site { siteMetadata { title description author keywords } } } `
  )

  const metaDescription = description || site.siteMetadata.description

  return (
    <Helmet
      htmlAttributes={{
        lang,}}title={title}
      tags={tags}
      titleTemplate={` %s | ${site.siteMetadata.title} `}meta={[
        {
          name: `description`,
          content: metaDescription}, {property: `og:title`,
          content: title}, {property: `og:description`,
          content: metaDescription}, {property: `og:type`,
          content: `website`,}, {name: `twitter:card`,
          content: `summary`,}, {name: `twitter:creator`,
          content: site.siteMetadata.author}, {name: `twitter:title`,
          content: title}, {name: `twitter:tags`,
          content: tags}, {name: `twitter:description`,
          content: metaDescription,},].concat(meta)} / >)} seo.defaultprops = {lang: 'zh-cn', meta: [], description: 'Technical blog',} seo.propTypes = {description: PropTypes.string, lang: PropTypes.string, meta: PropTypes.arrayOf(PropTypes.object), title: PropTypes.string.isRequired, } export default SEOCopy the code

Above is my example 🌰

Then add seo components to each component | | template or page

The optimized data for each page’s head meta title is the data passed in

Personalize it

There are also plugins like what typescript supports where do you search for installs

pit

I am using an NPM package that uses global objects such as Windows Document etc.

It was okay when Gatsby Develop was around

Gatsby Build will report an error!

Import breaks Gatsby Build : WebpackError: ReferenceError: Element is not defined

stack-overflow

Because runtime does not have a Page object when it is packaged, there are two solutions to this problem

  1. Check if there is a document object in use, if notnullDoes not perform
typeof window ! = ='undefined' &&  windows.open()
Copy the code

What if I use it in my NPM package? Can’t change the source code, I encountered this situation, encountered this situation to configure Webpack ignore

/ / ignore global object exports. OnCreateWebpackConfig = ({stage, loaders, actions}) = > {if (stage === "build-html") {
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /xxx-xxxx/,
            use: loaders.null(),
          },
        ],
      },
    })
  }
}
Copy the code

In some cases we reported an error while yarn add XXX

yarn add xxxx error “pngquant pre-build test failed”

  • Every time I install the package, I get the error pngquant pre-build test failed, macOS cannot install “libpng-dev”, only “libpng”

Install libpng and that’s it, issues

The deployment of

gatsby build

No more narration here, whether GitHub Pages/Netlify…… Just throw it up

GitHub Hooks + nodejs :juejin.cn/post/684490…

About

My Gatsby Blog is at new.ruoduan.cn

  • O star ⭐ ️ 🙏 🙏 🙏

Warehouse address: github.com/Chad97/my-G…