如何使用迁移的 HTML 内容为 Gatsby 创建博客条目

Bri*_*ter 2 gatsby

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

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

是否有某种方法可以将 HTML 添加到单独的 Javascript 文件中,以便将其包含在内(通过模板?)并且元数据位于降价文件中?

Der*_*yen 5

编辑:这是一个示例回购


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

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

root
 |--content
 |   `--htmls
 |       |--post1.html
 |       `--post2.html
 |  
 |--src
 |   `--templates
 |        `--blog.js
 |
 |--gatsby-config.js
 `--gatsby-node.js
Run Code Online (Sandbox Code Playgroud)

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

// gatsby-config.js
{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: `${__dirname}/content/htmls`,
    name: `html`,
  },
},
Run Code Online (Sandbox Code Playgroud)

然后在 中gatsby-node.js,您可以使用loadNodeContent读取原始 html。从那时起,它就非常简单了,只需按照 Gatsby 关于创建 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);
}
Run Code Online (Sandbox Code Playgroud)

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

{
  allHtmlContent {
    edges {
      node {
        name
        content
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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