Gatsby 블로그에 '게시물 편집' 버튼 추가

이 기사에서는 Gatsby 블로그에 "게시물 편집"버튼을 추가하는 방법을 살펴보겠습니다. 이 버튼을 클릭하면 사용자가 현재 보고 있는 블로그 게시물을 생성하는 데 사용된 github/gitlab의 마크다운 파일로 이동합니다.



설정



Gatsby 블로그에 편집 버튼을 추가하기 전에 Gatsby blog starter 를 사용하여 간단한 Gatsby 사이트를 설정해 보겠습니다. 이 단계를 건너뛰고 기존 사이트에 버튼을 추가할 수 있습니다.

npm -g install gatsby-cli
gatsby new my-blog-starter https://github.com/gatsbyjs/gatsby-starter-blog


위의 시작을 사용하지 않는 경우 gatsby-source-filesystem 플러그인이 설치되어 있는지 확인해야 합니다. 마크다운 파일을 가져오려면. 귀하의 gatsby-config.js는 다음과 같습니다.

  {
    resolve: `gatsby-source-filesystem`,
    options: {
      path: `${__dirname}/content/blog`,
      name: `blog`,
    },
  },


그런 다음 gatsby-transformer-remark 플러그인도 설치되어 있고 다음과 같이 gatsby-config.js에 있어야 합니다.

  {
    resolve: `gatsby-transformer-remark`,
    options: {
      // ...
    },
  },


(선택 사항) 블로그 게시물


gatsby-node.js 파일이 다음과 같다고 가정해 보겠습니다.

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;

  const blogPost = path.resolve(`./src/templates/blog-post.js`);
  const result = await graphql(
    `
      {
        allMarkdownRemark(
          sort: { fields: [frontmatter___date], order: DESC }
          limit: 1000
        ) {
          edges {
            node {
              fields {
                slug
              }
              frontmatter {
                title
              }
            }
          }
        }
      }
    `
  );

  if (result.errors) {
    throw result.errors;
  }

  // Create blog posts pages.
  const posts = result.data.allMarkdownRemark.edges;

  posts.forEach((post, index) => {
    const previous = index === posts.length - 1 ? null : posts[index + 1].node;
    const next = index === 0 ? null : posts[index - 1].node;

    createPage({
      path: post.node.fields.slug,
      component: blogPost,
      context: {
        slug: post.node.fields.slug,
        previous,
        next,
      },
    });
  });
};


이것이 각 마크다운 파일에 대한 새 블로그 게시물을 만드는 방법입니다. 마크다운이 Gatsby here 에서 작동하는 방식에 대해 자세히 알아볼 수 있습니다.

또한 블로그 게시물에 대한 간단한 템플릿 파일을 사용하겠습니다. 따라서 우리의 blog-post.js는 다음과 같습니다.

import React from "react";
import { Link, graphql } from "gatsby";

// ...

const BlogPostTemplate = ({ data, pageContext, location }) => {
  const post = data.markdownRemark;
  const siteTitle = data.site.siteMetadata.title;
  const { previous, next } = pageContext;

  return (
    <Layout location={location} title={siteTitle}>
      <SEO
        title={post.frontmatter.title}
        description={post.frontmatter.description || post.excerpt}
      />
      // ...
    </Layout>
  );
};

export default BlogPostTemplate;

export const pageQuery = graphql`
  query BlogPostBySlug($slug: String!) {
    site {
      siteMetadata {
        title
      }
    }
    markdownRemark(fields: { slug: { eq: $slug } }) {
      id
      excerpt(pruneLength: 160)
      html
      frontmatter {
        title
        date(formatString: "MMMM DD, YYYY")
        description
      }
    }
  }
`;


편집 버튼



자, 이제 마크다운 파일이 저장된 git의 프로젝트 위치에 대한 두 가지 정보가 필요합니다. 이 예에서는 여기에 있습니다https://gitlab.com/hmajid2301/articles. git repo에 있는 마크다운 파일의 경로도 필요합니다. 따라서 이 두 가지 정보를 결합하여 git의 마크다운 파일에 대한 URL을 얻을 수 있습니다.

먼저 마크다운 파일의 파일 경로를 가져올 방법이 필요합니다. GraphQL 쿼리를 사용하여 이를 수행할 수 있습니다. 제목 및 내용과 같은 다른 정보를 얻는 데 사용하는 것과 동일한 쿼리입니다. 쿼리의 fileAbsolutePath 부분에 markdownRemark를 추가하기만 하면 됩니다. 이것은 이름에서 알 수 있듯이 파일의 절대 경로(예: /home/haseeb/projects/personal/articles/34. Gatsby edit button/source_code/content/blog/hello-world/index.md )를 반환합니다.

export const pageQuery = graphql`
  query BlogPostBySlug($slug: String!) {
    site {
      siteMetadata {
        title
      }
    }
    markdownRemark(fields: { slug: { eq: $slug } }) {
      id
      excerpt(pruneLength: 160)
      html
      fileAbsolutePath
      frontmatter {
        title
        date(formatString: "MMMM DD, YYYY")
        description
      }
    }
  }
`;


이제 이 파일 경로를 사용하여 Gitlab에서 이 페이지로 연결하는 방법이 필요합니다. articles/ 가 git repo라는 것을 알고 있기 때문에 /home/haseeb/projects/personal/articles 에서 /home/haseeb/projects/personal/articles/34. Gatsby edit button/source_code/content/blog/hello-world/index.md 를 제거하려고 합니다.

그런 다음 마크다운 파일이 있는 저장소의 git URL이 https://gitlab.com/hmajid2301/articles 라고 가정합니다. git의 마크다운 파일 경로는 https://gitlab.com/hmajid2301/articles/-/blob/master/34. Gatsby edit button/source_code/content/blog/hello-world/index.md 와 같을 수 있습니다.

따라서 이 git URL을 생성하기 위해 blog-post.js 파일에 논리를 추가해 보겠습니다. GraphQL 쿼리를 업데이트한 후 코드에 일부 로직을 추가하여 git URL 경로를 연습할 수 있습니다. getGitMarkdownUrl() 라는 새 함수를 만들어 보겠습니다.

const BlogPostTemplate = ({ data, pageContext, location }) => {
  const post = data.markdownRemark;
  const siteTitle = data.site.siteMetadata.title;
  const { previous, next } = pageContext;

  function getGitMarkdownUrl() {
    const pathConst = "/articles/";
    const gitURL = "https://gitlab.com/hmajid2301/articles";
    const sliceIndex =
      post.fileAbsolutePath.indexOf(pathConst) + pathConst.length;
    const markdownFileGitPath = post.fileAbsolutePath.slice(sliceIndex);
    const blogPostOnGit = `${gitURL}/-/blob/master/${markdownFileGitPath}`;
    return blogPostOnGit;
  }

  const gitMarkdownUrl = getGitMarkdownUrl();

  // ....
};


Warn: Don't forget to change the gitURL variable in your project!



다음 두 줄은 /articles/ 이전의 모든 것을 제거하므로 34. Gatsby edit button/source_code/content/blog/hello-world/index.md 를 얻습니다.

const sliceIndex = post.fileAbsolutePath.indexOf(pathConst) + pathConst.length;
const markdownFileGitPath = post.fileAbsolutePath.slice(sliceIndex);


그런 다음 이것을 git URL과 결합하여 마크다운 파일https://gitlab.com/hmajid2301/articles/-/blob/master/34. Gatsby edit button/source_code/content/blog/hello-world/index.md의 경로로 끝납니다.

const blogPostOnGit = `${gitURL}/-/blob/master/${markdownFileGitPath}`;


마지막으로 편집 버튼을 추가하고 여기에 링크하도록 하기만 하면 됩니다gitMarkdownUrl. 아래와 같이 할 수 있습니다.

<a href={gitMarkdownUrl} rel="noreferrer" target="_blank">
  EDIT THIS POST
</a>


더 멋지게 보이게 하려면 react-icons를 사용하여 적절한 편집 아이콘을 얻을 수 있습니다(위의 gif 참조).

그게 다야! 사용자가 편집 버튼을 클릭하면 마크다운 파일이 있는 git repo로 이동하게 됩니다. 그런 다음 프로젝트를 분기하여 편집하고 새 병합 또는 끌어오기 요청(GitLab 대 GitHub)을 열고 원하는 변경 사항을 추가할 수 있습니다(귀하가 승인한 경우).

부록


  • Source Code
  • Site in video

  • Source code 동영상 사이트용
  • 좋은 웹페이지 즐겨찾기