rehype-pretty-code 使用教程

rehype-pretty-code 使用教程

rehype-pretty-codeBeautiful code blocks for Markdown or MDX.项目地址:https://gitcode.com/gh_mirrors/re/rehype-pretty-code

项目介绍

rehype-pretty-code 是一个用于美化代码块的 Rehype 插件。它可以将代码块转换为具有语法高亮的漂亮格式,支持多种编程语言。该插件基于 Shiki 和 Rehype,提供了丰富的主题和选项,使得代码展示更加美观和易读。

项目快速启动

安装

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

npm install rehype-pretty-code

使用

在你的项目中引入并使用 rehype-pretty-code

const rehypePrettyCode = require('rehype-pretty-code');
const rehype = require('rehype');

const html = `
  <pre><code class="language-javascript">
    const hello = 'world';
    console.log(hello);
  </code></pre>
`;

rehype()
  .use(rehypePrettyCode, {
    theme: 'dark-plus', // 选择一个主题
  })
  .process(html, (err, file) => {
    if (err) throw err;
    console.log(String(file));
  });

应用案例和最佳实践

案例一:博客中的代码高亮

假设你正在构建一个博客系统,希望在文章中展示代码块时能够自动进行语法高亮。你可以使用 rehype-pretty-code 来实现这一功能。

const rehype = require('rehype');
const rehypePrettyCode = require('rehype-pretty-code');

const blogPost = `
  <article>
    <h1>我的第一篇博客</h1>
    <p>下面是一个简单的 JavaScript 示例:</p>
    <pre><code class="language-javascript">
      function greet(name) {
        return 'Hello, ' + name + '!';
      }
      console.log(greet('World'));
    </code></pre>
  </article>
`;

rehype()
  .use(rehypePrettyCode, {
    theme: 'nord', // 选择一个主题
  })
  .process(blogPost, (err, file) => {
    if (err) throw err;
    console.log(String(file));
  });

案例二:文档网站中的代码示例

如果你正在构建一个文档网站,希望在文档中展示代码示例时能够自动进行语法高亮。你可以使用 rehype-pretty-code 来实现这一功能。

const rehype = require('rehype');
const rehypePrettyCode = require('rehype-pretty-code');

const documentation = `
  <section>
    <h2>快速开始</h2>
    <p>下面是一个简单的 React 组件示例:</p>
    <pre><code class="language-jsx">
      import React from 'react';

      function App() {
        return &lt;div&gt;Hello, World!&lt;/div&gt;;
      }

      export default App;
    </code></pre>
  </section>
`;

rehype()
  .use(rehypePrettyCode, {
    theme: 'one-dark-pro', // 选择一个主题
  })
  .process(documentation, (err, file) => {
    if (err) throw err;
    console.log(String(file));
  });

典型生态项目

rehype-pretty-code 可以与其他 Rehype 插件和工具链一起使用,以构建更强大的静态站点生成器或文档系统。以下是一些典型的生态项目:

  • Rehype: 一个用于处理 HTML 和 XML 的工具链。
  • Shiki: 一个用于语法高亮的工具,rehype-pretty-code 基于 Shiki。
  • MDX: 一个允许你在 Markdown 中使用 JSX 的工具,可以与 rehype-pretty-code 结合使用,以在文档中展示代码示例。

通过结合这些工具,你可以构建出功能强大且美观的文档和

rehype-pretty-codeBeautiful code blocks for Markdown or MDX.项目地址:https://gitcode.com/gh_mirrors/re/rehype-pretty-code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

谭沫彤

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

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

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

打赏作者

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

抵扣说明:

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

余额充值