Docusaurus feature
For this week, I found a couple of nice features from Docusaurus and I thought Code blocks feature is pretty cool and I'd like to add the feature to my static website general. For example, if you write 3 backticks with code in .md
file, you will see code blocks below:
function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}
Code Blocks source code in Docusaurus
Fist, I got into Docusaurus Repo and searched codes that I was looking for, my keyword was codeblocks
and there were some files involved with codeblocks. I could find the test file as well.
I found the unwrapMdxCodeBlocks
function under packages/docusaurus-utils/src/markdownUtils.ts
, and it returns code blocks after unwrapping the triple backticks.
export function unwrapMdxCodeBlocks(content: string): string {
// We only support 3/4 backticks on purpose, should be good enough
const regexp3 =
/(?<begin>^|\n)```
{% endraw %}
mdx-code-block\n(?<children>.*?)\n
{% raw %}
```(?<end>\n|$)/gs;
const regexp4 =
/(?<begin>^|\n)```
{% endraw %}
{% raw %}`mdx-code-block\n(?<children>.*?)\n`{% endraw %}
{% raw %}
```(?<end>\n|$)/gs;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const replacer = (substring: string, ...args: any[]) => {
const groups = args.at(-1);
return `${groups.begin}${groups.children}${groups.end}`;
};
return content.replaceAll(regexp3, replacer).replaceAll(regexp4, replacer);
}
I guess this function is used to unwrap code blocks and return to preprocessor.ts
, and also, Docusaurus
automatically picks up syntax highlighting and this is powered by Prism React Renderer
. However, I didn't really figure out how to convert that content into .html
file with using Prism React Renderer
.
I'm trying to implement the new feature in a similar way, but not exactly the same, so my plan is going to modify unwrapMdxCodeBlocks
function and apply Prism to highlight the code blocks.
Top comments (0)