코딩

MDX

코딩쪼렙 2023. 1. 12. 15:05
728x90

mdx: 마크다운+jsx

마크다운 + react

 

npm install gatsby-plugin-mdx @mdx-js/react

 

gatsby-plugin-mdx는 Gatsby와 함께 MDX를 사용하기 위한 공식 통합입니다. MDX는 마크다운 안에 포함된 JSX를 작성할 수 있습니다. 사소한 일에는 마크다운의 간결한 구문(예: # heading)을 사용하고 고급 구성 요소에는 JSX를 사용할 수 있기 때문에 훌륭한 조합입니다.

Usage

After installing gatsby-plugin-mdx you can add it to your plugins list in your gatsby-config.js. You’ll also want to configure gatsby-source-filesystem to point at your src/pages directory.

gatsby-config.js

gatsby.config.js파일에  `gatsby-plugin-mdx` 삽입하여 설정

module.exports = {
  plugins: [
    `gatsby-plugin-mdx`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `pages`,
        path: `${__dirname}/src/pages`,
      },
    },
  ],
}

서버 kill하고 재시작하여 빌드

 

해당파일들을 md->mdx로 수정

 

 

grahpql excerpt에  기본 글자제한이있고 글자제한을 둘 수도 있음.

 

+ excerpt는 작성 시 ##(h2)로 해야 나타나고 #(h1)은 나타나지 않음.

 

slug

url의 제목을 써 넣기위해 쓰는 것 

 

blog-post/hello.mdx

+Visual Studio Code를 사용하시는 분들 중, MDX 작성 시
---
title: Hello
---
를 입력하는 부분에서 글자의 색상이 표시되지 않는 분들은 Extensions에서 MDX 검색하셔서 "MDX"라는 익스텐션을 설치해보시기 바랍니다.

 

 

 

import { graphql, Link, PageProps } from "gatsby";
import React from "react";
import Layout from "../../components/Layout";
import Seo from "../../components/Seo";

export default function blogs({ data }: PageProps<Queries.BlogPostsQuery>) {
    return (
        <Layout title="Blog">
            <section>
                {data.allMdx.nodes.map((file, index) => (
                    <article key={index}>
                        <Link to={`/blog/${file.frontmatter?.slug}/`}>
                            <h3>{file.frontmatter?.title}</h3>
                            <h5>
                                {file.frontmatter?.author} in:{" "}
                                {file.frontmatter?.category}
                            </h5>
                            <h6>{file.frontmatter?.date}</h6>
                            <hr />
                            <p>{file.excerpt}</p>
                        </Link>
                    </article>
                ))}
            </section>
        </Layout>
    );
}

export const query = graphql`
    query BlogPosts {
        allMdx {
            nodes {
                frontmatter {
                    title
                    category
                    date(formatString: "YYYY.MM.DD")
                    author
                    slug
                }
                excerpt(pruneLength: 50)
            }
        }
    }
`;

 

해당 mdx의 slug로 파일,주소가만들어진다.

 

 

같은 컴포넌트를 이용

블로그 게시물 페이지 템플릿 만들기

MDX 노드의 slug 필드에서 새 페이지를 만들려면 src/pages/{mdx.frontmatter__slug}.js에 새 파일을 만들어야 합니다.
src/pages/{mdx.frontmatter__slug}.js는 데이터 계층의 각 MDX 노드에 대해 하나씩 여러 경로로 전환됩니다.
ex) Gatsby는 슬러그 my-first-post와 함께 MDX 노드를 사용하여 /my-first-post/ 경로에 있는 페이지를 빌드합니다.

https://www.gatsbyjs.com/docs/tutorial/part-6/#task-create-blog-post-page-template

 

Part 6: Create Pages Programmatically | Gatsby

Introduction In Part 5 , you added all of your blog posts to your Blog page. But that means that your Blog page will get longer and longer…

www.gatsbyjs.com

 

 

mdx magic

mdx  파일 본문을 

children으로 html내용을 받아올  수 있다.


interface IBlogPostProps {
    data: Queries.PostDetailQuery;
    children: any;
}

export default function BlogPost({ data, children }: IBlogPostProps) {
    console.log(children);
    return (
        <Layout title="Blog Post">
            <div>{children}</div>
        </Layout>
    );
}

export const query = graphql`
    query PostDetail($frontmatter__slug: String) {
        mdx(frontmatter: { slug: { eq: $frontmatter__slug } }) { //url (slug) 을 가지고 mdx내용들을 템플릿을 이용하여 편하게 작성함. 
            body
            frontmatter {
                author
                category
                date
                slug
                title
            }
        }
    }
`;

export const Head = ({ data }: IBlogPostProps) => (
    <Seo title={data.mdx?.frontmatter?.title} />
);

 

 

MDX를 사용하도록 데이터 변환
https://www.gatsbyjs.com/docs/tutorial/part-5/

글씨색 변경 extention 설치
1. Apollo GraphQL
2. GraphGL: Syntax Highlighting

 

 

static image

gatsby-plugin-image

높은 성능 점수를 유지하면서 반응형 이미지를 사이트에 추가하는 것은 수동으로 수행하기 어려울 수 있습니다. Gatsby Image 플러그인은 다양한 크기와 형식으로 이미지를 생성하는 어려운 부분을 처리합니다!
npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-sharp
https://www.gatsbyjs.com/plugins/gatsby-plugin-image

 

위와 같이 작성하고 graphiQL에서 이미지 확인가능

정적이미지 이미지를 수동으로 삽입할 때  <StaticImage>사용
동적이미지 미리 알 수 없는 이미지

객체로만듬

 

import { getImage, GatsbyImage } from "gatsby-plugin-image";

 

export default function BlogPost({ data, children }: IBlogPostProps) {
    const image = getImage(
        data.mdx?.frontmatter?.headerImage?.childImageSharp?.gatsbyImageData!
    );
    return (
        <Layout title="Blog Post">
            <GatsbyImage
                image={image as any}
                alt={data.mdx?.frontmatter?.title!}
            ></GatsbyImage>
            <div>{children}</div>
        </Layout>
    );
}

export const query = graphql`
    query PostDetail($frontmatter__slug: String) {
        mdx(frontmatter: { slug: { eq: $frontmatter__slug } }) {
            body
            frontmatter {
                author
                category
                date
                slug
                title
                headerImage {
                    childImageSharp {
                        gatsbyImageData(height: 450)
                    }
                }
            }
        }
    }
`;

Non-null assertion operator
data.mdx?.frontmatter?.headerImage?.childImageSharp?.gatsbyImageData! 에서 뒤에 !는 Non-null assertion operator로 피연산자가 Nullish(null이나 undefined) 값이 아니라고 타입스크립트에게 단언하는 것입니다. 즉, 앞의 값이 null 또는 undefined가 아님을 확신할 때 사용할 수 있습니다.
(하지만 ! 대신 if문을 사용하는 것을 추천)