Gatsby精粹,面向将来的blog

先贴个人新blog地址 ==> new.ruoduan.cn/javascript

旧的html

缘起

我原先是使用的hexo的,这里咱们从hexo ==> Gatsby的缘由以下:前端

  1. 都是静态页面框架,SEO,部署等,静态页面的优点
  2. 使用现代化框架开发 —— React ,能够不断的迭代
  3. 社区资源成熟,目前Gatsby的插件已经很是成熟 连接
  4. 性能强悍,相比其余的静态页面框架,Gatsby的性能比较出众
  5. GraphQL 来请求数据, 灵活 优雅,待会介绍

install

安装全局 gastby 命令行,经过这个初始化脚手架。 yarn global add gastby-clijava

script

  • develop
  • build
  • serve

结构-范式

├── content
├── gatsby-browser.js
├── gatsby-config.js // 主要配置文件
├── gatsby-node.js // 视图层配置
├── package.json
├── public
├── src
    ├── components // 组件
    ├── pages // 页面文件
    ├── templates // 模版文件

复制代码

Gatsby 采用约定式路由,page文件夹要注意,全都是采用小写命名,例如:node

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

另外在生产页面的时候 createPage 能够手动设置路由,可是仍是建议遵照约定react

Data

数据层,Gatsby 使用的是Graphql,文档webpack

Gatsby 是自带 图像调试界面的git

http://localhost:8000/___graphqles6

___graphql

🔥蕾丝 这样的一个界面,稍后讲解他的简单使用

⚠️注意:能够经过右边的Query 查询参数,方便的一批~

在Gatsby中的数据分为2种

  1. 文件数据
  2. 配置数据

经过插件实现

gatsby-source-filesystem读本地文件列表,

query {
   allFile {
      edges {
        node {
          relativePath
          prettySize
          extension
          birthTime(fromNow: true)
        }
      }
    }
复制代码

经过 gatsby-transformer-remark 读 markdown 文件内容

const result = await graphql(
    ` { allMarkdownRemark( sort: { fields: [frontmatter___date], order: DESC } limit: 1000 ) { edges { node { fields { slug } frontmatter { date(formatString: "YYYY 年 MM 月 DD 日") title tags } } } } } `
  )
复制代码

应该注意到了吧 我上面的 graphql 有稍许不一样,我在获取markdown的时候对他进行了排序,根据时间date 的倒序排序, 还吧时间格式化了如下,它能作的远不止这些 还包括 sortfilterskiplimit 等参数对数据作处理. 详情可看文档

Gatsby 中的数据都是经过 Promise 来实现的, 例如要拿到上面的 markdown 文件内容

能够 经过 await 或者 直接 .then (res => { ... })

—— 下面是获取配置数据 也就是 gatsby-config.js 的数据

query {
    site {
      siteMetadata {
        title
      }
    }
复制代码

个人配置文件结构如👇

module.exports = {
  siteMetadata: {
    title: `Ruoduan' Blog`, author: `Ruoduan`, description: `个人介绍...`, siteUrl: `https://github.com/Chad97`, keywords: 'react, 前端, python, js, ', }, }, plugins: [ 安装的插件 配置 ...... ], } 复制代码

一目了然了吧 ~~

黑魔法

在Gatsby page 页面中想要获取数据只须要经过:👇

export const pageQuery = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC },
      ) {
      edges {
        node {
          excerpt
          fields {
            slug
          }
          frontmatter {
            date(formatString: "YYYY 年 MM 月 DD 日")
            title
            tags
            categories
          }
        }
      }
    }
  }
`
复制代码

只须要 export 导出一个graphql 获取到到数据就会就会挂载到当前页面到 props 上,是否是很神奇 🚀🚀🚀

useStaticQuery

除了上面的方式 咱们想在组件中拿到一些数据该怎么办呢?

Gatsby 有一种很是优雅的方式 ———— useStaticQuery

useStaticQuery 和 上面方式不一样 这里拿到的数据只存在于当前组件的 runtime,

例以下面一个组件 我要拿到全部文章标题

import { useStaticQuery, graphql } from "gatsby"
const data = useStaticQuery(graphql` query titleQuery { allMarkdownRemark { edges { node { frontmatter { title } } } } } `)
  
  const [titleData, setTitle] = useState(data.allMarkdownRemark.edges)
  useStaticQuery 必须放在组件开头 ,也就是 数据变量以前

复制代码

是否是有殊途同归之妙啊~ 👏 👏 👏

createPages

咱们在面对一些重复的页面好比 blog 文章详情页面 ,只是数据不同其余的同样, 咱们不可能每一个markdown都建立一个 page 页面,这时候 咱们就须要使用createPages 建立页面

createPage({
      path: post.node.fields.slug,
      component: blogPost,
      context: {
        slug: post.node.fields.slug,
        previous,
        next,
      },
复制代码

三个参数:

  • path: 路由地址,我这里使用的是文章标题

  • component: 模版

  • context: 传递到该页面的数据

我这里建立页面是 利用 上面 获取全部 markdown 的数据来建立文章详情页

const result = await graphql(
    ` { allMarkdownRemark( ...... 如上 } `
  )
  // 获取md数据
const posts = result.data.allMarkdownRemark.edges

const blogPost = path.resolve(`./src/templates/blog-post.js`)
  // 建立详情页
  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,
      },
    })
  })
复制代码

Develop Tools

  • babel

.babelrc,而后 gatsby 安装 babel-preset-gatsby,和咱们平时没有太大差异,只是安装的包不一样罢了

  • webpack

webpack 想要自定义配置

gatsby-node.js

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
  if (stage === "build-html") {
    actions.setWebpackConfig({
      module: {
        rules: [
          ......
        ],
      },
    })
  }
}
复制代码

stage 有分为:

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

Other

PWA 支持

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` // 这个插件必须在 manifest 后面
]
复制代码

proxy

两种方式,

  1. gatsby-config.js 里配 proxy,和 umi 或 webpack-dev-server 的相似
  2. gatsby-node.js 里配 developMiddleware,手写中间件

SEO

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

{
  siteMetadata: {
    // 这三个属性必需要有
    title: `Destiny'Note`,
    author: `destiny`,
    description: `my own blog`,
    keywords: `react, graphql, gatsby`
  },
  plugins: [
    //...
    `gatsby-plugin-react-helmet`
  ]
}
复制代码

在 src/components 下增长 seo.js 文件:

/** * 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: `若端的技术博客`, } SEO.propTypes = { description: PropTypes.string, lang: PropTypes.string, meta: PropTypes.arrayOf(PropTypes.object), title: PropTypes.string.isRequired, } export default SEO 复制代码

以上是个人示例🌰

而后把 seo 组件添加到各个 组件||模版 or 页面中去

SEO-例子

每一个页面的 head meta title 的优化数据就是 传入的数据

个性化 设置吧

还有一些 例如 typescript 支持什么的 plugins哪里搜索安装就行了

我是用的一个 npm 包中 使用了 全局对象 如 :windows document 等。

gatsby develop 的时候是没事的

gatsby build 就会报错 !

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

stack-overflow

是由于 在打包的时候 runtime 并无 page 对象,解决这个问题有2中方案

  1. 在使用的地方 判断当前 有没有 document 对象,没有的话就 null 不执行
typeof window !== 'undefined' &&  windows.open()
复制代码

那若是是 个人npm 包中使用了呢? 总不能 改源码吧,我就是遇到的这种状况,遇到这种状况就要 配置 webpack 忽略

// 忽略全局对象
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
  if (stage === "build-html") {
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /xxx-xxxx/,
            use: loaders.null(),
          },
        ],
      },
    })
  }
}
复制代码

有些状况下 咱们在 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"

安装 libpng 就行了 issues

部署

gatsby build

这里就很少作 叙述了,不论是 GitHub Pages / Netlify ...... , 往上扔就能够了

这里链一个 个人 部署方式: GitHub Hooks + nodejs 实现 自动化部署:juejin.im/post/5e19d4…

About

个人Gatsby Blog 地址new.ruoduan.cn

  • 求star ⭐️ 🙏🙏🙏

仓库地址github.com/Chad97/my-G…

相关文章
相关标签/搜索