Created
June 16, 2023 17:14
-
-
Save dev-sampsonorson/c8157cce735c03b485f9ab0d4f93f40a to your computer and use it in GitHub Desktop.
Dynamic import with pipe and hightlight.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// hightlight-language.ts | |
import hljs from 'highlight.js/lib/core'; | |
import bash from 'highlight.js/lib/languages/bash'; | |
import markdown from 'highlight.js/lib/languages/markdown'; | |
import scss from 'highlight.js/lib/languages/scss'; | |
import typescript from 'highlight.js/lib/languages/typscript'; | |
import yaml from 'highlight.js/lib/languages/yaml'; | |
const langHightlighters = { | |
bash, | |
css: scss, | |
markdown, | |
typescript, | |
yaml, | |
javascript: typescript, | |
}; | |
const registerLanguageHighlighters = () => { | |
Object.entries(langHightlighters).forEach(([langName, highlighter]) => { | |
hljs.registerLanguage(langName, highlighter); | |
}); | |
return hljs; | |
}; | |
export const hightlightJS = registerLanguageHighlighters(); | |
// ---------------------------- | |
// Pipe | |
import { Pipe, PipeTransform } from '@angular/core'; | |
import { Observable, from, of, map } from 'rxjs'; | |
@Pipe({ name: 'hightlight' }) | |
export class HightlightPipe implements PipeTransform { | |
transform(value: string, lang?: string): Observable<string> { | |
return value | |
? from(import('./hightlight-language')).pipe(map(({ hightlightJS }) => { | |
return lang ? hightlightJS.highlight(lang, value) : hightlightJS.highlight(value); | |
})) | |
: of(''); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment