React组件未在GatsbyJS的MDX markdown文件中呈现

时间:2019-08-21 04:34:45

标签: reactjs components markdown gatsby

无法在GatsbyJS网站中的MDX Markdown文件中呈现ReactJS组件。

我有一个gatsbyjs静态站点,该站点使用由MDX(JSX支持的Markdown)支持的博客引​​擎。预期的行为是,根据MDX功能,嵌入在MDX降价文件中的React组件应与MDX降价文件中其余的标记一起呈现。

这是gatsby-config.js文件:

const path = require('path')

module.exports = {
  siteMetadata: {
    title: 'Gatsby Starter MDX Basic',
    description:
      'Kick off your next, great Gatsby project with this default starter.
  },
  plugins: [
    'gatsby-plugin-react-helmet',
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `pages`,
        path: `${__dirname}/src/pages`
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `blog`,
        path: `${__dirname}/src/pages/blog`
      }
    },
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
       {
    resolve: `gatsby-transformer-remark`,
    options: {
      plugins: [
        {
          resolve: `gatsby-remark-images`,
          options: {
            // It's important to specify the maxWidth (in pixels) of
            // the content container as this plugin uses this as the
            // base for generating different widths of each image.
            maxWidth: 590,
          },
        },
      ],
    },
  },

    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        extensions: ['.mdx', '.md'],
        defaultLayouts: { default: path.resolve('./src/components/blog-post-layout.js') },
    mdPlugins: [
       require('remark-images'),
       require('remark-slug'),
       require('remark-autolink-headings')
    ],
    gatsbyRemarkPlugins: [
         {
        resolve: 'gatsby-remark-images',
              options: {
                  maxWidth: 1200,
              },
          },
     ],
      },
    },
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: 'gatsby-default-mdx-basic',
        short_name: 'starter',
        start_url: '/',
        background_color: '#663399',
        theme_color: '#663399',
        display: 'minimal-ui',
        icon: 'src/images/gatsby-icon.png', // This path is relative to the root of the site.
      },
    },
    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.app/offline
    // 'gatsby-plugin-offline',
  ],
}

这是用于创建页面和节点的gatsby-node.js文件:

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

// Here we're adding extra stuff to the "node" (like the slug)
// so we can query later for all blogs and get their slug
exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions
  if (node.internal.type === 'Mdx') {
    const value = createFilePath({ node, getNode })
    createNodeField({
      // Name of the field you are adding
      name: 'slug',
      // Individual MDX node
      node,
      // Generated value based on filepath with "blog" prefix
      value: `/blog${value}`
    })
  }
}

// Programmatically create the pages for browsing blog posts
exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions
  return graphql(`
    query {
      allMdx(sort: { order: DESC, fields: [frontmatter___date] }) {
        edges {
          node {
            id
            excerpt(pruneLength: 250)
            fields {
              slug
            }
            frontmatter {
              author
              title
            }
          }
        }
      }
    }
  `).then((results, errors) => {
    if (errors) return Promise.reject(errors)
    const posts = results.data.allMdx.edges

    // This little algo takes the array of posts and groups
    // them based on this `size`. I used a small number just
    // for testing since there are only three posts
    let size = 2
    let start = 0
    let groupedPosts = Array.from(Array(Math.ceil(posts.length / size)))
    groupedPosts = groupedPosts.map(() => {
      const group = posts.slice(start, start + size)
      start += size
      return group
    })

    groupedPosts.forEach((group, index) => {
      const page = index + 1
      createPage({
        path: `/blog/${page}`,
        component: path.resolve('./src/components/browse-blog-posts.js'),
        context: { groupedPosts, group, page }
      })
    })
  })
}

最后是带有嵌入式ReactJS组件的Markdown(MDX)文件:

---
path: 'apple'
title: 'Apple Services'
date: 2018-11-18T12:33:46+10:00
author: 'Srikanth'
image: 'services/default.png'
---

import { Box, Heading, Text } from 'rebass'

import {
  FacebookShareButton,
  LinkedinShareButton,
  TwitterShareButton,
  WhatsappShareButton,
  PinterestShareButton,
  EmailShareButton,
} from 'react-share'

import {
  FacebookShareCount,
  PinterestShareCount,
  VKShareCount,
  OKShareCount,
  RedditShareCount,
  TumblrShareCount,
} from 'react-share'


# Here is a JSX block
It is using imported components!

<Box>
  <Heading>Here's a JSX block</Heading>
  <Text>It's pretty neat</Text>
</Box>


# Here’s a Social Share


<FacebookShareButton
            url='http://github.com'
            quote='GitHub'
            className="Demo__some-network__share-button">
            <FacebookIcon
              size={32}
              round />
          </FacebookShareButton>

Lorem markdownum aequalis strigis. _Saetigeri iubeas_, vultu huic alvum nondum
de obside ut laniavit arbor palmis, cum quin. Rupes vetat videndo, armigerae
crimen habet Priamum nec.

![gatsbyjs-logo](./gatsbyjs-logo.jpg)

## Ne verba patulosque numen vix libet



Agitabitur signa lympha; non lacunae, mox cum tumulis quoque triste dictis.
Ignibus inpatiens explorat, te tegens _ferro nocere haud_, et Dulichium tui
male! Quo sed [fuit flexit et](#vexant-achivi) hic die solido, gloria?

1. Cum det dixit Parcarum qui spemque est
2. Exit ex huic
3. Quod consiste agitataque claustraque vicina videt lacertis
4. Loquor videt
5. Ardua non igne caelesti coniugis cognovi diversorum
6. Per nunc pariterque saeva vindicet

Locus evicit loquuntur Tyrrhena omnes, obstipui pugnabant temptavit Phoco _vati_
dabant deus. Memorata haberet sepulcrales gentisque dum sic, in flumina templa!
Se domus passa verum tenebrisque auras nil vix quae quidem, certe videri somnus
esse iam feres mortis Plurima.

## Postquam tamen

Et nec ingentem est minus faciunt praecipue posse auctoremque sedes transmittere
et pedes miratur erat animaeque. Tellus admonuit humanam funes, sagittis et
licet! Inserui quamvis Clymeni.

- Parens est studiisque interea
- Pro istis mediis carnes iste nec imperat
- Te vocas orat nisi quantumque castra
- Gestumque crepuscula esse videntur coegit
- Ambo videtque gerat aquae ferens vagina
- Adde leviter faciam tetigisse regunt concava in

Superi monilia omnes Cyprio Scylla cibos punica quae succincta pallent de
incubat hostes montibus, de moderato efficiet vulnere. Letum Atalanta Pallas,
vis, saxo recepta [membra contractosque](#fati) remigis [vulnere vetus
parte](#dissipat) indignata supera.

Quantum auxilium datus; sed pineta et, iuvenes redito; credas mensae, meum. Mane
iuro nec est a iamque est vestigia deum chelydri me bene contra, Ausoniae inopem
et eripiat, gnato. Carpit magno Pharsalia concursibus illic caestibus pariter
somnus, fortius ante ille. Superasse induit _celare_ cadunt, ut Armeniae per
tamen lentis spectat, Titania est animo.

0 个答案:

没有答案