Gatsby 框架内置插件系统,插件是为应用添加功能的最好的方式。
在 Gatsby 中有三种类型的插件:
Gatsby 官方提供了非常多且非常有用的插件,开发者也可以自己编写插件,以及发布供他人使用。
Gatsby 对插件的命名规范有要求:
source
transformer
plugin
在根目录下创建 json
文件夹,在里面添加 products.json
文件。
json\products.json
:
[{"title": "Vans范斯 男子短袖T恤 Work Weird新款运动休闲TEE迷彩官方正品","price": 208,"url": "/images/product-1.jpg","address": "上海","id": "1"},{"title": "小ck女包包2020新款潮真皮斜挎包女百搭ins2019单肩包时尚手提包","price": 239,"url": "/images/product-2.webp","address": "北京","id": "2"},{"title": "潮牌羊毛开衫男川久爱心毛衣保桃心play外套玲","price": 118,"url": "/images/product-3.webp","address": "深圳","id": "3"},{"title": "太平鸟男装 2020秋季pupu熊联名时尚大图案毛套衫圆领帅气针织衫","price": 379,"url": "/images/product-4.webp","address": "广州","id": "4"}
]
JSON 中使用的图片放置在根目录的 static
文件夹中。
static
文件夹是静态资源文件夹,里面的资源在浏览器中可以直接访问,例如 http://localhost:8000/images/product-1.jpg
可以访问 static/images/product-1.jpg
文件。
将本地 JSON 文件中的数据放入数据层需要安装两个插件:
gatsby-source-filesystem
:用于将本地文件中的数据添加至数据层gatsby-transformer-json
:将原始 JSON 字符串转换成 Javascript 对象安装完成后,需要将插件配置到 gatsby-config.js
中:
// gatsby-config.js
/*** Configure your Gatsby site with this file.** See: https://www.gatsbyjs.com/docs/gatsby-config/*/module.exports &#61; {// siteMetadata 对象用于配置网站元数据siteMetadata: {title: "Hello Gatsby",author: "Jone",},/* Your site config here */plugins: [{resolve: "gatsby-source-filesystem", // 插件名options: {// 分类名称&#xff0c;用于区分不同数据&#xff0c;可以不设置name: "json",// 插件将转化 path 文件夹下的 json 文件// 最终以<文件名Json>为数据名存储到数据层path: &#96;${__dirname}/json/&#96;,},},// 不需要特殊配置的可以直接放到 plugin 数组中"gatsby-transformer-json",],
}
query MyQuery {allFile {nodes { # 转化的文件absolutePath # 文件的绝对路径publicURL # 转化后的文件所在路径ext # 文件的扩展名}}productsJson { # 转化的数据&#xff08;查询单个数据&#xff1a;只查询第一条&#xff09;titleurlpriceaddress}allProductsJson { # 转化的数据&#xff08;查询全部数据&#xff09;nodes {titleurl # 取的 JSON 数据的 url 字段的值priceaddress}}
}
图像优化
static
json
.json
文件)的路径&#xff0c;难以分析出图片的真实存储位置gatsby-source-filesystem
&#xff1a;用于将本地文件信息添加到数据层gatsby-plugin-sharp
&#xff1a;提供本地图像的处理功能&#xff08;调整图像尺寸、压缩体积等&#xff09; gatsby-transformer-sharp
&#xff1a;将 gatsby-plugin-sharp
插件处理后的图像信息添加到数据层 gatsby-source-filesystem
添加到数据层&#xff0c;则会将 url
的 GraphQL 查询结果替换为图片信息对象gatsby-image
&#xff1a;React 组件&#xff0c;优化图像显示&#xff0c;基于gatsby-transformer-sharp
插件转化后的数据。srcset
和 sizes
属性&#xff0c;不同宽度的设备加载合适大小的图片// gatsby-config.js
/*** Configure your Gatsby site with this file.** See: https://www.gatsbyjs.com/docs/gatsby-config/*/module.exports &#61; {// siteMetadata 对象用于配置网站元数据siteMetadata: {title: "Hello Gatsby",author: "Jone",},/* Your site config here */plugins: [{resolve: "gatsby-source-filesystem", // 插件名options: {// 分类名称&#xff0c;用于区分不同数据&#xff0c;可以不设置name: "json",// 插件将转化 path 文件夹下的 json 文件// 最终以<文件名Json>为数据名存储到数据层path: &#96;${__dirname}/json/&#96;,},},// 不需要特殊配置的可以直接放到 plugin 数组中"gatsby-transformer-json","gatsby-plugin-sharp","gatsby-transformer-sharp",],
}
将图像文件夹 images
从 static
移动到数据文件所在的 json
文件夹下。
修改数据中的图像路径&#xff1a;"/images/xxxx" -> "./images/xxxx"
。
重启项目 gatsby develop
&#xff0c;打开 GraphQL 调试页面。
查询数据多了 allImageSharp
和 imageSharp
节点&#xff0c;而 JSON 数据项的 url
节点也增加了相应节点&#xff1a;
query MyQuery {allImageSharp {nodes {fixed { # 固定大小的图片&#xff08;可以生成指定宽高的图片&#xff09;src}fluid { # 响应大小的图片src}}}allProductsJson {nodes {titlepriceaddressurl {childImageSharp {fluid {# 响应图片相关属性srcsrcSetsizesaspectRatio # 像素比}fixed(width:200,height:200) { # 指定宽高srcsrcSetwidthheight}}}}}
}
响应式图片&#xff1a;
// src\pages\product.js
import React from "react"
import { graphql } from "gatsby"
import Img from "gatsby-image"export default function Product({ data }) {return (<div>{data.allProductsJson.nodes.map((node, index) &#61;> (<div key&#61;{index}><p>{node.title}</p><p>{node.address}</p><p>{node.price}</p><div style&#61;{{ width: 400 }}>{/* fluid 接收响应式图片 图片的宽以父元素为准 */}<Img fluid&#61;{node.url.childImageSharp.fluid} /></div></div>))}</div>)
}// 响应式图片
export const query &#61; graphql&#96;query {allProductsJson {nodes {titleurl {childImageSharp {fluid {srcsrcSetsizesaspectRatio}}}priceaddress}}}
&#96;
固定大小图片&#xff1a;
// src\pages\product.js
import React from "react"
import { graphql } from "gatsby"
import Img from "gatsby-image"export default function Product({ data }) {return (<div>{data.allProductsJson.nodes.map((node, index) &#61;> (<div key&#61;{index}><p>{node.title}</p><p>{node.address}</p><p>{node.price}</p><div style&#61;{{ width: 400 }}>{/* fixed 接收固定大小图片 图片的宽高固定 */}<Img fixed&#61;{node.url.childImageSharp.fixed} /></div></div>))}</div>)
}// 固定大小图片
export const query &#61; graphql&#96;query {allProductsJson {nodes {titleurl {childImageSharp {fixed(width: 200, height: 200) {srcsrcSetheightwidth}}}priceaddress}}}
&#96;
将本地 Markdown 数据添加到数据层
添加文件 /posts/gatsby.md
&#xff1a;
---
title: "Hello Gatsby"
date: "2048-01-05"
---Hello Gatsby, this is a post.
添加文件 /posts/react.md
&#xff1a;
---
title: "Hello React"
date: "9012-12-23"
---This is a test markdown file![](./images/1.jpg)
添加图片 /posts/images/1.jpg
gatsby-source-filesystem
&#xff1a;将 Markdown 文件数据放入数据层 gatsby-transformer-remark
&#xff1a;将数据层中的原始 Markdown 数据转化成可用的对象形式// gatsby-config.js
/*** Configure your Gatsby site with this file.** See: https://www.gatsbyjs.com/docs/gatsby-config/*/module.exports &#61; {// siteMetadata 对象用于配置网站元数据siteMetadata: {title: "Hello Gatsby",author: "Jone",},/* Your site config here */plugins: [{resolve: "gatsby-source-filesystem", // 插件名options: {// 分类名称&#xff0c;用于区分不同数据&#xff0c;可以不设置name: "json",// 插件将转化 path 文件夹下的 json 文件// 最终以<文件名Json>为数据名存储到数据层path: &#96;${__dirname}/json/&#96;,},},{resolve: "gatsby-source-filesystem",options: {name: "markdown",path: &#96;${__dirname}/posts/&#96;,},},// 不需要特殊配置的可以直接放到 plugin 数组中"gatsby-transformer-json","gatsby-plugin-sharp","gatsby-transformer-sharp","gatsby-transformer-remark",],
}
重新启动 gatsby develop
。
GraphQL 调试页面的查询数据中多了 allMarkdownRemark
和 markDownRemark
节点&#xff1a;
query MyQuery {allMarkdownRemark {nodes {html # 解析的内容部分frontmatter {date # 解析的 date 字段title # 解析的 title 字段}fileAbsolutePath # markdown 文件的绝对路径internal { # 内部属性type # 标识文件内部得一个类型&#xff0c;用于区分文件类型&#xff0c;如 markdown 文件、json 文件、页面文件等}}}
}
// src\pages\list.js
import React from "react"
import Header from "../components/Header"
import { graphql } from "gatsby"export default function List({ data }) {return (<div>List Page<Header /><hr />{data.allMarkdownRemark.nodes.map(post &#61;> (<div key&#61;{post.id}><p>{post.frontmatter.title}</p><p>{post.frontmatter.date}</p><div dangerouslySetInnerHTML&#61;{{ __html: post.html }}></div></div>))}</div>)
}export const query &#61; graphql&#96;query {allMarkdownRemark {nodes {idhtmlfrontmatter {datetitle}}}}
&#96;
构建文章详情页
为每篇文章的数据添加 slug
&#xff08;访问路径&#xff09;作为请求标识&#xff0c;slug
值为文件名称。
gatsby.md -> /posts/gatsby
react.md -> /posts/react
添加方式有两种&#xff1a;
slug
属性slug
属性在 gatsby-node.js
文件中导出一个 onCreateNode
方法&#xff0c;该方法在创建每个节点&#xff08;Node&#xff09;后被调用。
Gatsby 应用启动时&#xff0c;会先启动插件&#xff0c;通过插件从外部数据源获取数据&#xff0c;然后将获取到的数据添加到数据层中&#xff0c;向数据层中每添加一条数据实际上就是创建一个数据节点&#xff0c;每创建完一个数据节点&#xff0c;Gatsby 都会调用一次 onCreateNode
方法。
onCreateNode
是框架为开发者提供的用于修改节点信息的方法。
onCreateNode
接收的参数中可以解构出 node
对象&#xff0c;就是 Gatsby 创建的数据节点&#xff1a;
type
属性&#xff0c;可以获取当前节点的内部类型&#xff0c;区分 Markdown 文件。fileAbsolutePath
文件绝对路径属性&#xff0c;获取文件名作为 slug
的值。最后使用从 actions
对象中解构的 createNodeField
方法为数据添加属性&#xff0c;方法接受三个参数&#xff1a;
node
&#xff1a;要添加属性的数据节点对象name
&#xff1a;要添加的属性的名字value
&#xff1a;要添加的属性的值// gatsby-node.js
const path &#61; require("path")// 为数据节点添加属性
function onCreateNode({ node, actions }) {const { createNodeField } &#61; actionsif (node.internal.type &#61;&#61;&#61; "MarkdownRemark") {const slug &#61; path.basename(node.fileAbsolutePath, ".md")createNodeField({node,name: "slug",value: slug,})}
}module.exports &#61; { createPages, onCreateNode }
重启 gatsby develop
createNodeField
添加的属性&#xff0c;会添加到 nodes
节点下的 fields
属性下。
query MyQuery {allMarkdownRemark {nodes {htmlfrontmatter {datetitle}fields {slug}}}
}
使用 createPages
编程式创建页面&#xff1a;
graphql
方法&#xff0c;用于查询数据 gatsby
模块中的 graphql
方法不同context
传递给页面的数据&#xff0c;可以在页面中使用的查询命令中作为参数接收 $<参数名>
// gatsby-node.js
const path &#61; require("path")// 创建文章详情页
async function createPages({ graphql, actions }) {// 获取模板绝对路径const template &#61; require.resolve("./src/templates/post.js")// 获取组件所需数据// 注意此处的 graphq 和 组件中使用的 graphql 传参方式不一样const { data } &#61; await graphql(&#96;query {allMarkdownRemark {nodes {fields {slug}}}}&#96;)// 根据模板和数据创建页面const { createPage } &#61; actionsdata.allMarkdownRemark.nodes.forEach(node &#61;> {createPage({path: &#96;/posts/${node.fields.slug}&#96;, // 页面访问地址component: template, // 模板绝对路径// 组件中使用的查询命令可以通过 &#96;$slug&#96; 接收传递给页面的参数context: {slug: node.fields.slug,},})})
}// 为数据节点添加属性
function onCreateNode({ node, actions }) {const { createNodeField } &#61; actionsif (node.internal.type &#61;&#61;&#61; "MarkdownRemark") {const slug &#61; path.basename(node.fileAbsolutePath, ".md")createNodeField({node,name: "slug",value: slug,})}
}module.exports &#61; { createPages, onCreateNode }
// src\templates\person.js
import React from "react"
import { graphql } from "gatsby"export default function Post({ data }) {return (<div><p>{data.markdownRemark.frontmatter.title}</p><p>{data.markdownRemark.frontmatter.date}</p><div dangerouslySetInnerHTML&#61;{{ __html: data.markdownRemark.html }}></div></div>)
}export const query &#61; graphql&#96;query ($slug: String) {markdownRemark(fields: { slug: { eq: $slug } }) {htmlfrontmatter {datetitle}id}}
&#96;
处理 Markdown 文件中的图片
react.md
中插入了一个图片 ./images/1.jpg
&#xff0c;在转化数据时&#xff0c;并没有将 Markdown 数据中的图片地址替换为这个图片资源文件转化后的路径。
gatsby-remark-images
插件用于处理 Markdown 中的图片&#xff0c;将图片路径替换为转化后的资源路径&#xff0c;以及一些其它优化。
安装 npm i gatsby-remark-images
该插件要作为 gatsby-transformer-remark
的插件去配置&#xff1a;
// gatsby-config.js
/*** Configure your Gatsby site with this file.** See: https://www.gatsbyjs.com/docs/gatsby-config/*/module.exports &#61; {// siteMetadata 对象用于配置网站元数据siteMetadata: {title: "Hello Gatsby",author: "Jone",},/* Your site config here */plugins: [{resolve: "gatsby-source-filesystem", // 插件名options: {// 分类名称&#xff0c;用于区分不同数据&#xff0c;可以不设置name: "json",// 插件将转化 path 文件夹下的 json 文件// 最终以<文件名Json>为数据名存储到数据层path: &#96;${__dirname}/json/&#96;,},},{resolve: "gatsby-source-filesystem",options: {name: "markdown",path: &#96;${__dirname}/posts/&#96;,},},// 不需要特殊配置的可以直接放到 plugin 数组中"gatsby-transformer-json","gatsby-plugin-sharp","gatsby-transformer-sharp",{resolve: "gatsby-transformer-remark",options: {plugins: [{resolve: "gatsby-remark-images",options: {maxWidth: 600, // 生成图片的最大宽度&#xff0c;默认 650linkImagesToOriginal: false, // 是否将图片包裹在 a 标签中},},],},},],
}