将RSS添加到Next.js MDX博客,同时使用NodeJS的"RSS"模块.如何将MDX转换为H



当前,我在将MDX转换为HTML时遇到问题。

我为顺风博客做这件事

Github上的完整代码→https://github.com/tailwindlabs/blog.tailwindcss.com

这是相关代码:

scripts/build-rss.js

import fs from 'fs'
import path from 'path'
import getAllPostPreviews from '../src/getAllPostPreviews'
import RSS from 'rss'
const siteUrl = 'https://blog.tailwindcss.com'
const feed = new RSS({
title: 'Blog – Tailwind CSS',
site_url: siteUrl,
feed_url: `${siteUrl}/feed.xml`,
})
getAllPostPreviews().forEach(({ link, module: { meta, default: html } }) => {
console.log(html)
const postText = `<div style="margin-top=55px; font-style: italic;">(The post <a href="${siteUrl + link}">${meta.title}</a> appeared first on <a href="${siteUrl}">Tailwind CSS Blog</a>.)</div>`;
feed.item({
title: meta.title,
guid: link,
url: `https://blog.tailwindcss.com${link}`,
date: meta.date,
description: meta.description,
custom_elements: [{
"content:encoded": html + postText
}].concat(meta.authors.map((author) => ({ author: [{ name: author.name }] }))),
})
})
fs.writeFileSync('./out/feed.xml', feed.xml({ indent: true }))

html变量记录到控制台:

[Function: MDXContent] { isMDXComponent: true }

如何获得纯HTML?

这比我想象的要复杂一些

我将resourceQuery: /rss/添加到next.config.js中,类似于:

next.config.js

{
resourceQuery: /rss/,
use: [
...mdx,
createLoader(function (src) {
return this.callback(null, src)
}),
],
},

getAllPostPreviews.js中使用了上述rss查询,添加了一个新函数getAllPosts,如:

getAllPostPreviews.js

export function getAllPosts() {
return importAll(require.context('./pages/?rss', true, /.mdx$/)).sort((a, b) =>
dateSortDesc(a.module.meta.date, b.module.meta.date)
)
}

我从Post.js导出了mdxComponents,类似于:

Post.js

export const mdxComponents = {
...
}

最后,将scripts/build-rss.js改为使用ReactDOMServer.renderToStaticMarkup(),方法是将其包装在MDXProvider中,如:

import ReactDOMServer from 'react-dom/server'
import { MDXProvider } from '@mdx-js/react'
import { mdxComponents } from '../src/components/Post'
import { getAllPosts } from '../src/getAllPostPreviews'
getAllPosts().forEach(({ link, module: { meta, default: Content } }, i) => {
const mdx = <MDXProvider components={mdxComponents}><Content /></MDXProvider>
const html = ReactDOMServer.renderToStaticMarkup(mdx)
...
}

这个想法来自https://ianmitchell.dev/blog/building-a-nextjs-blog-rss&https://github.com/IanMitchell/ianmitchell.dev

相关内容

  • 没有找到相关文章

最新更新