gloriaJun / gloria-tilog

My develop log....story
https://gloriajun.github.io/gloria-tilog/
MIT License
1 stars 0 forks source link

[Page] Configure to write the content by using markdown #49

Closed gloriaJun closed 4 years ago

gloriaJun commented 4 years ago

Description :memo:

Configure to write the content by using markdown

Reference

To Do :mag:

gloriaJun commented 4 years ago

Installation

yarn add gatsby-transformer-remark

Configuration

 plugins: [
     // ...SKIP...
    'gatsby-transformer-remark',
  ],

Create the sample makrdown file

'/posts/sample.md'

---
title: 'Sweet Pandas Eating Sweets'
date: '2017-08-10'
---

Pandas are really sweet.

Here's a video of a panda eating sweets.

<iframe width="560" height="315" src="https://www.youtube.com/embed/4n0xNbfJLR8" frameborder="0" allowfullscreen></iframe>

Create the template component

import React from 'react';

const PostTemplate: React.FC = props => {
  return (
    <code>
      <pre>{JSON.stringify(props, null, 4)}</pre>
    </code>
  );
};

export default PostTemplate;

Configure gatsby-node.js

const path = require('path');
/**
 * Implement Gatsby's Node APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/node-apis/
 *
 */

// You can delete this file if you're not using it
// Implement the Gatsby API “createPages”. This is called once the
// data layer is bootstrapped to let plugins create pages from data.
exports.createPages = async ({ actions, graphql, reporter }) => {
  const { createPage } = actions;

  // Query for markdown nodes to use in creating pages.
  const result = await graphql(
    `
      query {
        allMarkdownRemark(limit: 10) {
          edges {
            node {
              id
              html
              frontmatter {
                title
                date
              }
            }
          }
        }
      }
    `,
  );

  // Handle errors
  if (result.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`);
    return;
  }

  // Create pages for each markdown file.
  const blogPostTemplate = path.resolve(`src/templates/post/index.tsx`);

  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    const {
      id,
      frontmatter: { title, date },
    } = node;

    createPage({
      path: '/test',
      component: blogPostTemplate,

      // In your blog post template's graphql query, you can use path
      // as a GraphQL variable to query for data from the markdown file.
      context: {
        id,
        title,
        date,
      },
    });
  });
};

Check through the web

blog-md-plugin
gloriaJun commented 4 years ago

TypeScript with gatsby-node.js

Installation

ts-node를 이용하면 TypeScript를 이용하여 정의를 할 수 있다.

yarn add ts-node

Configuration

gatsby-node.js 파일을 아래와 같이 수정한다.

'use strict';

require('ts-node').register();

const { createPages } = require('./src/config/createPages');
exports.createPages = createPages;

./src/config/createPages.ts 파일을 생성하고, 해당 파일에 TypeScript 기반으로 작성한다.

import * as path from 'path';
import { CreatePagesArgs } from 'gatsby';

const resolve = (dir: string) => path.resolve(__dirname, '..', dir);

/**
 * Implement Gatsby's Node APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/node-apis/
 *
 */

// You can delete this file if you're not using it
// Implement the Gatsby API “createPages”. This is called once the
// data layer is bootstrapped to let plugins create pages from data.
export const createPages = async ({
  actions,
  graphql,
  reporter,
}: CreatePagesArgs) => {
  const { createPage } = actions;

  // Query for markdown nodes to use in creating pages.
  const { errors, data } = await graphql(
    `
      query {
        allMarkdownRemark(limit: 10) {
          edges {
            node {
              id
              html
              frontmatter {
                title
                date
              }
            }
          }
        }
      }
    `,
  );

  // Handle errors
  if (errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`);
    return;
  }

  // Create pages for each markdown file.
  const blogPostTemplate = resolve(`templates/post/index.tsx`);

  data.allMarkdownRemark.edges.forEach(({ node }: any) => {
    const {
      id,
      html,
      frontmatter: { title, date },
    } = node;

    createPage({
      path: '/test',
      component: blogPostTemplate,

      // In your blog post template's graphql query, you can use path
      // as a GraphQL variable to query for data from the markdown file.
      context: {
        id,
        title,
        html,
        date,
      },
    });
  });
};
gloriaJun commented 4 years ago

Type definition for graphql

graphql 스키마에 대한 타입이 추적되지 않는 이슈를 해결하기 위한 환경 설정

Installation

yarn add gatsby-plugin-codegen

Configuration

// gatsby-config.js
plugins: [
    // other plugins
    {
        resolve: 'gatsby-plugin-codegen',
        options: {},
    },
],
gloriaJun commented 4 years ago

Using mdx

Installation

yarn add gatsby-plugin-mdx @mdx-js/mdx @mdx-js/react
gloriaJun commented 4 years ago

To set path with sourceInstanceName

path에 gatsby-config의 아래와 같이 지정한 name을 prefix로 붙이고 싶었다.

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

그래서 찾아보니 아래와 같은 소스를 발견!! https://github.com/gatsbyjs/gatsby/blob/d1dac916b0763de786317c6a8d3dec5144b78d99/packages/gatsby-theme-blog-core/gatsby-node.js

이렇게 코드를 수정해서...원하는 방향으로 구현~

  if (node.internal.type === `Mdx`) {
    // const type = node.frontmatter.type;
    const filePath = createFilePath({ node, getNode });
    const path = filePath.replace('/blog/', '').replace(/(^\/|\/$)/, '');

    const fileNode = getNode(node.parent);
    const source = fileNode.sourceInstanceName;

    createNodeField({
      name: `slug`,
      value: `/${source}/${path}`,
      node,
    });

결과적으로 아래 이미지 처럼 blog 폴더 내부의 컨텐츠들은 /blog/xxxx와 같이 경로를 정의되어 나오게 하였다. image