remark-rehype 使用教程

remark-rehype 使用教程

remark-rehypeplugin that turns markdown into HTML to support rehype项目地址:https://gitcode.com/gh_mirrors/re/remark-rehype

项目介绍

remark-rehype 是一个用于将 Markdown 转换为 HTML 的插件,支持 rehype。它是 remark 生态系统的一部分,remark 是一个强大的 Markdown 处理器,而 rehype 是一个 HTML 处理器。通过使用 remark-rehype,开发者可以轻松地将 Markdown 内容转换为 HTML,以便在网页上显示。

项目快速启动

安装

首先,你需要安装 remark-rehype 及其依赖项:

npm install remark-rehype rehype-stringify remark-parse unified

基本使用

以下是一个简单的示例,展示如何使用 remark-rehype 将 Markdown 转换为 HTML:

import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import rehypeStringify from 'rehype-stringify';

const file = await unified()
  .use(remarkParse)
  .use(remarkRehype)
  .use(rehypeStringify)
  .process('# Hello, world!')

console.log(String(file));

运行上述代码将输出:

<h1>Hello, world!</h1>

应用案例和最佳实践

支持 HTML 嵌入

如果你需要在 Markdown 中嵌入 HTML,可以使用 allowDangerousHtml 选项:

import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import rehypeStringify from 'rehype-stringify';

const file = await unified()
  .use(remarkParse)
  .use(remarkRehype, { allowDangerousHtml: true })
  .use(rehypeStringify, { allowDangerousHtml: true })
  .process('<a href="/wiki/Dysnomia_(moon)" onclick="alert(1)">Dysnomia</a>')

console.log(String(file));

输出:

<p><a href="/wiki/Dysnomia_(moon)" onclick="alert(1)">Dysnomia</a></p>

安全处理嵌入的 HTML

为了防止 XSS 攻击,建议使用 rehype-rawrehype-sanitize

import rehypeSanitize from 'rehype-sanitize';
import rehypeStringify from 'rehype-stringify';
import rehypeRaw from 'rehype-raw';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import { unified } from 'unified';

const file = await unified()
  .use(remarkParse)
  .use(remarkRehype, { allowDangerousHtml: true })
  .use(rehypeRaw)
  .use(rehypeSanitize)
  .use(rehypeStringify)
  .process('<a href="/wiki/Dysnomia_(moon)" onclick="alert(1)">Dysnomia</a>')

console.log(String(file));

输出:

<p><a href="/wiki/Dysnomia_(moon)">Dysnomia</a></p>

典型生态项目

  • remark: 一个强大的 Markdown 处理器。
  • rehype: 一个 HTML 处理器。
  • rehype-raw: 支持解析嵌入的 HTML 节点。
  • rehype-sanitize: 用于 sanitize HTML,防止 XSS 攻击。
  • rehype-stringify: 将 HTML 树转换为字符串。

通过这些工具的组合使用,开发者可以构建出强大且安全的 Markdown 到 HTML 转换流程。

remark-rehypeplugin that turns markdown into HTML to support rehype项目地址:https://gitcode.com/gh_mirrors/re/remark-rehype

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

薄正胡Plains

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值