Syntax Highlighting with PrismJS

Overview

Prism is a lightweight, extensible syntax highlighter that can be used when working with code blocks in markdown files in blog posts.

It is possible to define a language for the code to be used in the Scully code like this:

```typescript
const foo = 'bar';
```

How Scully Handles Code Blocks

Scully parses the markdown using marked, and the parsed result looks like this:

<code class="language-ts">
  <span class="token keyword">const</span> foo
  <span class="token operator">=</span>
  <span class="token string">'bar'</span>
  <span class="token punctuation">;</span>
</code>

marked uses the CSS class prefix language- to tag the code block with an appropriate language.

Usage

To highlight the code blocks use prismjs and create a service like this:

npm i --save prismjs
ng g s highlight

The service will include all languages needed. The code looks like this:

import { Injectable, Inject } from '@angular/core';

import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

import 'clipboard';
import 'prismjs';
import 'prismjs/plugins/toolbar/prism-toolbar';
import 'prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard';
import 'prismjs/components/prism-bash';
import 'prismjs/components/prism-css';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-json';
import 'prismjs/components/prism-markup';
import 'prismjs/components/prism-typescript';
// ... probably more, check out node_modules/prismjs/components

declare var Prism: any;

@Injectable({ providedIn: 'root' }) // <-- FYI providedIn NOT IN ORIGINAL DOCS
export class HighlightService {
  constructor(@Inject(PLATFORM_ID) private platformId: Object) {}

  highlightAll() {
    if (isPlatformBrowser(this.platformId)) {
      Prism.highlightAll();
    }
  }
}

Now, it needs to inject the service in the BlogComponent that was generated by Scully:

import {/* ... */, AfterViewChecked} from '@angular/core';
import {HighlightService} from '../highlight.service';
/* ... */
export class BlogComponent implements OnInit, AfterViewChecked {
  constructor(
    /* ... */
    private highlightService: HighlightService
  ) {}
  /* ... */
  ngAfterViewChecked() {
    this.highlightService.highlightAll();
  }
}

Finally, include a Prism's theme like this:

/* include CSS for prism toolbar */
@import '~prismjs/plugins/toolbar/prism-toolbar.css';
/* check node_modules/prismjs/themes/ for the available themes */
@import '~prismjs/themes/prism-tomorrow';

Visit prismjs for more information.