Adding highlighting in a markdown-based blog
Add syntax highlights to markdown code
If you are using something like Remark you can simply add remark-prism to your markdown processing as follows.
import { remark } from 'remark'
import emoji from 'remark-emoji'
import gfm from 'remark-gfm'
import html from 'remark-html'
import prism from 'remark-prism'
/*
Using remark to convert markdown to HTML:
- prism for code syntax highlighting
- gfm for tables
- emoji
*/
export async function markdownToHTML(markdown) {
const result = await remark()
.use(html, { sanitize: false })
.use(gfm)
.use(prism)
.use(emoji)
.process(markdown)
return result.toString()
}
Add css
Then, make sure you load a prism css theme to actually colorize your code.
import 'prismjs/themes/prism-tomorrow.css'
import '../styles/index.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
Adding highlighting to HTML directly
In this case we will be moving some of the work from the server to the client
Install prism js using npm / yarn
npm i prismjs
yarn add prismjs
Prismjs also provides TypeScript support, npm i @types/prismjs
or yarn add @types/prismjs
Use prismjs on your page
Import prismjs into your blog page and highlight all. The next step is just import prismjs into your codes and call the highlightAll function in your useEffect / componentDidMount.
import Prism from 'prismjs';
import "prismjs/components/prism-java"; // if you need a specific language
import 'prismjs/themes/prism-tomorrow.css'; // css theme
export default function Index() {
useEffect(() => {
if (typeof window !== 'undefined') { // don't run on server
Prism.highlightAll();
}
}, []);
return (
<pre class="language-javascript" >
<code>
function getFullName (user) {
const fullName = user.firstName + user.lastName;
return fullName;
}
</code>
</pre>
);
}
It will automatically select the code blocks and will highlight them all. Note, you must have your code in the format above.