gatsby md(remark) 에서 mdx 컨버팅하기

June 08,2020

, 3 min read


MDX?

MDX = Markdown + JSX

왜 MDX?

gatsby 에서는 포스트 작성시 md 보다는 mdx 를 사용하면 더 좋다(?).

  • mdx 에서는 컴포넌트 사용이 가능

  • 기존 remark plugin들도 사용할수 있음

컨버팅하자

어떻게??

기존 markdown을 mdx 로 바꾸자!

allMarkdownRemark -> allMdx

markdownRemark ->mdx

// blog-post-template.js
import { MDXRenderer } from "gatsby-plugin-mdx"
html -> body 

<section dangerouslySetInnerHTML={{ __html: post.html }} />
-> <MDXRenderer>{post.body}</MDXRenderer> 

install & uninstall

npm install --save gatsby-plugin-mdx gatsby-plugin-feed-mdx @mdx-js/mdx @mdx-js/react
npm uninstall --save gatsby-transformer-remark gatsby-plugin-feed

gatsby-config.js

{
-  resolve: `gatsby-transformer-remark`,
+  resolve: `gatsby-plugin-mdx`,   options: {
+    extensions: [`.mdx`, `.md`],-    plugins: [
+    gatsbyRemarkPlugins: [       {
         resolve: `gatsby-remark-images`,
         options: {
           maxWidth: 590,
         },
       },
       {
         resolve: `gatsby-remark-responsive-iframe`,
         options: {
           wrapperStyle: `margin-bottom: 1.0725rem`,
         },
       },
       `gatsby-remark-prismjs`,
       `gatsby-remark-copy-linked-files`,
       `gatsby-remark-smartypants`,
     ],
   },
  },

gatsby-node.js

- allMarkdownRemark(
+ allMdx(
- const posts = result.data.allMarkdownRemark.edges
+ const posts = result.data.allMdx.edges
- if (node.internal.type === `MarkdownRemark`) {
+ if (node.internal.type === `Mdx`) {

index.js

- const posts = data.allMarkdownRemark.edges
+ const posts = data.allMdx.edges
- allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
+ allMdx(sort: { fields: [frontmatter___date], order: DESC }) {

blogTemplate

- const post = this.props.data.markdownRemark
+ const post = this.props.data.mdx
# line 93
- markdownRemark(fields: { slug: { eq: $slug } }) {
+ mdx(fields: { slug: { eq: $slug } }) {
+ import { MDXRenderer } from "gatsby-plugin-mdx"
- html
+ body
- <section dangerouslySetInnerHTML={{ __html: post.html }} />
+ <MDXRenderer>{post.body}</MDXRenderer>

참고