Syntax Highlight Code in Markdown Posts | ATLASSC.NET
Skip to main content
/// .DATA.FRAGMENT_20221110

Syntax Highlight Code in Markdown Posts

1 minAuthor: Z.SHINCHVEN

I wrote this TypeScript full stack blogging web app for myself serving posts written in Markdown.

As a programmer, I write a lot of code in my posts, and I want to syntax highlight them for better readability.

highlight.js is a popular syntax highlighter, and it supports over 200 languages.

Here's how I do it...

Transform Markdown to HTML with highlight.js CSS Class

To do so, I used the following packages:

  • showdown - The Markdown parser I use to transform Markdown to HTML.
  • showdown-highlight - An extension for showdown to support syntax highlight.
import showdown from 'showdown';
import showdownHighlight from 'showdown-highlight';

// Create showdown converter
export const showdownConverter = new showdown.Converter({
  tables: true,
  // Configure extensions
  extensions: [showdownHighlight({
    pre: true,
    auto_detection: true,
  })],
});

// The markdown string with code block
const markdown = '```typescript\nconst a = 1;\n```';

// Now I have the HTML string with highlight.js CSS class in pre tag.
const html = showdownConverter.makeHtml(markdown);

Others extensions for showdown.

Import highlight.js CSS in My React App

There are a bunch of styles provided by highlight.js, choose one you like.

import 'highlight.js/styles/github.css';

It's done.

RackNerd Billboard Banner
Share node:
/// .RELATED.DATA_STREAMSShared tags

Related posts

Scanning_database_for_correlations…

/// .UPLINK.SUBSCRIBE

Keep your deck synced with every new transmission from ATLASSC.NET. Subscribe over RSS or Atom, or wire the whole archive straight into your AI assistant with the MCP server.