项目作者: kbravh

项目描述 :
Gatsby plugin that adds a gatsby-source-filesystem source name to Mdx nodes for enhanced querying in GraphQL.
高级语言: JavaScript
项目地址: git://github.com/kbravh/gatsby-plugin-mdx-source-name.git
创建时间: 2020-07-03T17:25:38Z
项目社区:https://github.com/kbravh/gatsby-plugin-mdx-source-name

开源协议:MIT License

下载


Description

Add a gatsby-source-filesystem source name to Mdx nodes for enhanced querying in GraphQL.

How to install

Install with npm:

  1. npm install gatsby-plugin-mdx-source-name

or with yarn:

  1. yarn add gatsby-plugin-mdx-source-name

When do I use this plugin?

This plugin is very useful if you are using multiple instances of gatsby-source-filesystem as it will allow you to query the name field from the source plugin on your Mdx nodes.

Examples of usage

Add this plugin to you gatsby-config.js file. Be sure to also include the gatsby-source-filesystem plugin, and add a name for the mdx files in the source plugin.

  1. plugins: [
  2. `gatsby-plugin-mdx-source-name` ,
  3. {
  4. resolve: `gatsby-source-filesystem` ,
  5. options: {
  6. path: `${__dirname}/src/blog` ,
  7. name: `blog` // this name will be added to the Mdx nodes
  8. }
  9. }
  10. ]

The source name will now be available to query via GraphQL:

  1. const query = graphql`
  2. query {
  3. allMdx(){
  4. nodes {
  5. id
  6. fields {
  7. source
  8. }
  9. }
  10. }
  11. }`

For example, if you wanted to filter by this new source field on page creation, you could do the following:

  1. // gatsby-node.js
  2. exports.createPages = ({actions, graphql}) => {
  3. const {createPage} = actions
  4. // query for all Mdx pages
  5. const query = graphql(`
  6. query {
  7. allMdx(){
  8. nodes {
  9. fields {
  10. source
  11. }
  12. frontmatter {
  13. slug
  14. }
  15. }
  16. }
  17. }
  18. `)
  19. return query.then(result => {
  20. // filter by source name "blog"
  21. const posts = result.data.allMdx.nodes.filter(node => node.fields.source === 'blog')
  22. posts.forEach(node => {
  23. createPage({
  24. path: `/blog/${node.frontmatter.slug}`,
  25. component: path.resolve('src/templates/blog-post.js'),
  26. context: {
  27. slug: node.frontmatter.slug
  28. }
  29. })
  30. })
  31. })
  32. }