【问题标题】:How can I create blog entries for Gatsby with migrated HTML content如何使用迁移的 HTML 内容为 Gatsby 创建博客条目
【发布时间】:2019-06-23 12:35:53
【问题描述】:

我正在尝试迁移博客,并且可以提取 HTML 格式的帖子以及标题、关键字、数据、元描述等。

如何使用它们在 GatsbyJS 中创建博客文章?我只能找到使用 Markdown 的说明。由于复杂的格式以及一些内联 CSS 样式,手动迁移数百个并将它们转换为 markdown 是不可行的。

有没有办法将 HTML 添加到单独的 Javascript 文件中,以便包含(通过模板?)并且元数据在 markdown 文件中?

【问题讨论】:

    标签: gatsby


    【解决方案1】:

    编辑:这里是an example repo


    我认为您可以将 gatsby-source-filesystem 指向您的 html 文件夹并为其中的每个文件创建一个节点。一旦你有了它,你就可以在你的模板中查询它们,就像使用其他 Markdown 节点一样。

    假设您在内容文件夹中有 html:

    root
     |--content
     |   `--htmls
     |       |--post1.html
     |       `--post2.html
     |  
     |--src
     |   `--templates
     |        `--blog.js
     |
     |--gatsby-config.js
     `--gatsby-node.js
    

    gatsby-source-filesystem 指向您的 html 文件夹:

    // gatsby-config.js
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/content/htmls`,
        name: `html`,
      },
    },
    

    然后在gatsby-node.js 中,您可以使用loadNodeContent 读取原始html。从那时起它就非常简单了,只需按照 Gatsby 的文档中关于 creating node 的这个示例进行操作即可。

    const { createContentDigest } = require("gatsby-core-utils");
    
    exports.onCreateNode = async ({
      node, loadNodeContent, createNodeId, actions
    }) => {
    
      // only care about html file
      if (node.internal.type !== 'File' || node.internal.mediaType !== 'text/html') return;
      
      const { createNode } = actions;
    
      // read the raw html content
      const nodeContent = await loadNodeContent(node);
    
      // set up the new node
      const htmlNodeContent = {
        id: createNodeId(node.relativePath), // required
        content: nodeContent,
        name: node.name, // take the file's name as identifier
        internal: {
          type: 'HTMLContent',
          contentDigest: createContentDigest(nodeContent), // required
        }
        ...otherNecessaryMetaDataProps
      }
    
      createNode(htmlNodeContent);
    }
    

    创建节点后,您可以使用以下命令查询它们

    {
      allHtmlContent {
        edges {
          node {
            name
            content
          }
        }
      }
    }
    

    从那时起,几乎将它们视为其他降价节点。如果您需要解析内容(例如定位图像文件等),它会变得更加复杂。在这种情况下,我认为您需要查看rehype 之类的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多