A remark plugin for transforming code blocks into code previews
npm install @thinke/remark-plugin-code-preview> 从remark-code-preview修改
You can install @thinke/remark-plugin-code-preview using npm or yarn:
``bash`
npm install @thinke/remark-plugin-code-preview --save-devor
pnpm install -D @thinke/remark-plugin-code-preview
To use @thinke/remark-plugin-code-preview in your remark-based Markdown processing pipeline, you need to configure your remark processor with this plugin. Here's an example of how to do it:
Say we have the following file example.mdx:
``mdExample
`html preview title="Code title"`Hello, World!``
And our module example.js looks as follows:
`js
import { readFile } from 'node:fs/promises'
import { remark } from 'remark'
import rehypeRaw from 'rehype-raw'
import rehypeStringify from 'rehype-stringify'
import remarkCodePreview from 'remark-code-preview'
import remarkRehype from 'remark-rehype'
remark()
.use(remarkCodePreview)
.use(remarkRehype, { allowDangerousHtml: true })
.use(rehypeRaw)
.use(rehypeStringify, { allowDangerousHtml: true })
.process(await readFile('example.mdx'), (err, file) => {
if (err) throw err
console.log(String(file))
})
`
Now, running node example.js yields:
`html`Example
Hello, World!
<div class='foo'>Hello, World!</div>
The Remark Code Preview Plugin accepts the following options:
The code preview template to use. You can customize the preview layout using placeholders like {preview}, {code}, codefence meta data (e.g. {title}), and your custom data.
The default template looks like this:
`html`
{preview}
{code}
You can customize the template according to your needs. For example:
`js
import { readFile } from 'node:fs/promises'
import { remark } from 'remark'
import remarkCodePreview from 'remark-code-preview'
const customTemplate =
{preview}
remark()
.use(remarkCodePreview, { template: customTemplate })
.process(await readFile('example.mdx'), (err, file) => {
if (err) throw err
console.log(String(file))
})
`
Yields:
`mdExample
Hello, World!
`
Data to interpolate into the template. You can provide additional data to be used in the template.
By default, the plugin throws a MissingValueError when a placeholder resolves to undefined. Setting this option to true ignores it and leaves the placeholder as is.
Whether to support MDX compiler.
Performs an arbitrary operation for each interpolation. You can define a custom transformation function for the interpolated values.
Default transformation:
`js``
;({ value }) => value