Gatsby Markdown 内联图像

Gatsby Markdown Inline Images

所以我想弄清楚如何呈现内联到我的博客的图像 post。我在顶部确实有一张特色图片可以使用,但不知道如何获取内联图片。

图像存储在src/images/

办公室-upgrade.md

---
title: "Office Upgrade"
image: ../images/office1.jpg
featured: false
author:
  name: "jrock2004"
date: "2017-08-06"
tags:
  - general
---

So, when I moved into our new house 3 yrs ago, my only requirement was I have my own office. In my last house I was stuck in the basement. When I made videos, I would get the jokes about living in my moms basement. As you can see, all the cords where just all over the place. It was just so bad.

![Nightmare Cable Management](../images/office2.jpg)

盖茨比-config.md

  plugins: [
    'gatsby-plugin-postcss',
    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        extensions: [`.mdx`, `.md`],
      },
    },
    'gatsby-plugin-image',
    'gatsby-plugin-sharp',
    'gatsby-transformer-sharp',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'images',
        path: `${__dirname}/src/images/`,
      },
      __key: 'images',
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'pages',
        path: './src/pages/',
      },
      __key: 'pages',
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 800,
            },
          },
        ],
      },
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'posts',
        path: `${__dirname}/src/posts/`,
      },
      __key: 'posts',
    },
  ],

component/post/index.tsx

<article className={`markdown mt-12 mx-auto ${image && 'w-11/12'}`}>
  <MDXProvider components={components}>
    <MDXRenderer>{body}</MDXRenderer>
  </MDXProvider>
</article>

当我查看 DOM 时,这就是呈现的内容

<img src="images/office2.jpg" alt="Nightmare Cable Management">

我做错了什么?

images/office2.jpg 下的图像是自动呈现的,因为它位于降价正文的下方。当你这样做时:

<MDXRenderer>{body}</MDXRenderer>

它会自动渲染里面的所有东西。

如您所说,您可以访问每个单独的降价节点(titleimagefeatured 等),但您无法控制正文元素。

MDXProvider provides 一堆自定义组件来优化和覆盖默认渲染行为:

import { MDXProvider } from "@mdx-js/react"

const YourH1 = props => <h1 style={{ color: "tomato" }} {...props} />
const YourParagraph = props => (
  <p style={{ fontSize: "18px", lineHeight: 1.6 }} {...props} />
)
const YourImg = props => <figure><img src={props.url} alt={props.alt}></img><figcaption{props.title}/figcaption></figure>


const components = {
  h1: YourH1,
  p: YourParagraph,
  img: YourImg
}

export const wrapRootElement = ({ element }) => (
  <MDXProvider components={components}>{element}</MDXProvider>
)

如您所见,这包装了 gatsby-ssr.jsgatsby-browser.js API,它允许您自定义图像组件。

MDXProvider 图像,产生以下 props:

{
  type: 'image',
  url: 'https://example.com/favicon.ico',
  title: 'bravo',
  alt: 'alpha'
}

来源:https://github.com/syntax-tree/mdast#image