我通过 webpack 加载器在 Node 模块中导入了一个 markdown 文件
import mardownFile from './markdownfile.md'
此文件是一本教科书,章节之间用##/h2 标记分隔
现在,我正在寻找一种方法将其转换为一个 json 对象,每个 h2 标签(或其他可能的包装器)位于单独的章节 block 中,以与页面内容作为 props.children 的 react 页面组件一起使用。有关我要解决的问题的更多详细信息
我的 markdown.md 文件里有这个
#Title
##Chapter 1
text text
text
##Chapter 2
text
etc
##Chapter 3
more text
image
我想阅读这个 markdown 并将其转换为一个对象,类似这样...
var aText = {
pages: [
{
"title": "Chapter 1.",
"text": "text",
},
{
"title": "Chapter 2.",
"text": "text",
},
{
"title": "Chapter 3.",
"text": "text",
"img": "cat-stevens.png",
}
]}
然后在 javascript react 组件中渲染一个像这样的页面组件
<Page page={aText.pages[0]} />
我在 mac osx 计算机上,但这是个人 Web 客户端项目,我试图在标准浏览器中解析它,我使用的是 Chrome,完成此操作的最佳方法是什么,有什么建议吗?
最佳答案
您不能导入 md 文件,因为导入只适用于 javascript 文件。 您需要使用一些 Markdown 解析器或编写自己的解析器。例如markdown-it :
var MarkdownIt = require('markdown-it');
var md = new MarkdownIt();
var result = md.parse('# markdown-it rulezz!');
console.log(result);
您将获得:
[Token {
type: 'heading_open',
tag: 'h1',
attrs: null,
map: [0, 1],
nesting: 1,
level: 0,
children: null,
content: '',
markup: '#',
info: '',
meta: null,
block: true,
hidden: false
},
Token {
type: 'inline',
tag: '',
attrs: null,
map: [0, 1],
nesting: 0,
level: 1,
children: [[Object]],
content: 'markdown-it rulezz!',
markup: '',
info: '',
meta: null,
block: true,
hidden: false
},
Token {
type: 'heading_close',
tag: 'h1',
attrs: null,
map: null,
nesting: -1,
level: 0,
children: null,
content: '',
markup: '#',
info: '',
meta: null,
block: true,
hidden: false
}]
关于javascript - 将 markdown 转换为 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40442058/