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 <div>Hello, World!</div>;
}
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
结合使用,以在文档中展示代码示例。
通过结合这些工具,你可以构建出功能强大且美观的文档和