Part 3. GatsbyJS How to enable Code Highlighting in MDX pages
Choose and install a code highlighter plugin
Personnaly I choose gatsby-remark-highlight-code because it looked good, and I made it work fairly easily with the doc provided. gatsby-remark-highlight-code
>npm install --save gatsby-transformer-remark gatsby-remark-highlight-code @deckdeckgo/highlight-code
Language supported : see prismjs
Other possibilities :
Configure the plugin
Edit gatsby-config.js and replace the line
`gatsby-remark-highlight-code`,
by the following code :
|
|
Add Imports in layout
For this example to stay easy, we will update the layout component by adding the code below after the imports in the file :
|
|
And that’s it. Now let’s see the result
Create a mdx with a code block
in the blog folder, let’s create a new mdx file : post2.mdx
Add the following content :
---
title: My Second Post with Code
---
# Post 2
## Part 1
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam diam est, mattis id justo at, tempus facilisis lorem. Vivamus auctor, nisl vel interdum sollicitudin, libero nisl malesuada massa, fringilla lobortis urna eros sit amet enim. Nulla eros nisi, laoreet a mollis nec, pellentesque ac metus. Integer maximus erat sed ipsum vehicula, sit amet consequat justo euismod. In orci neque, consectetur sed luctus eget, pharetra sed ante. Vestibulum enim nisi, faucibus sit amet ultrices faucibus, maximus sed nibh. Ut a lacinia diam. Proin tempus ipsum mi, sed auctor nunc convallis eu.
## Some Code
// This is some Comments
// and more comments
private class foo()
{
private string mydata = "something";
private void Show()
{
Console.WriteLine(mydata);
}
}
## Part 2
Curabitur nunc quam, ultricies sed tortor nec, iaculis interdum mi. Aliquam laoreet ipsum commodo, euismod augue in, consequat nunc. Aenean dui lorem, dignissim nec blandit vel, ullamcorper in mauris. Vivamus quis orci mi. Fusce at fermentum metus, non pulvinar nisl. In non justo sed lacus facilisis iaculis. Sed venenatis eget urna suscipit posuere. Nulla egestas dapibus metus, in dapibus nunc molestie a. Suspendisse commodo, augue molestie bibendum consequat, turpis urna aliquet justo, sit amet placerat elit dolor eu odio. Ut condimentum, eros ut maximus lacinia, nibh mauris egestas lectus, at venenatis mi turpis ac lectus.
It is possible to enclose the code between 2 lines of and also to force a specific language (as defined in Prism) by using
csharp at the beginning of a C# block of code for instance. The block must be terminated with ```