Created
May 2, 2019 18:29
-
-
Save Akryum/2985328af5f47b7d3b79900390bd2e4f to your computer and use it in GitHub Desktop.
This file contains 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
import Prism from 'prismjs' | |
import loadLanguages from 'prismjs/components/index.js' | |
import path from 'path' | |
loadLanguages() | |
const languages = [ | |
{ test: /\.(html|vue|xml)$/, lang: 'markup' }, | |
{ test: /\.js$/, lang: 'javascript' }, | |
{ test: /\.sh$/, lang: 'bash' }, | |
{ test: /\.coffee$/, lang: 'coffeescript' }, | |
{ test: /\.gql$/, lang: 'graphql' }, | |
{ test: /\.hx$/, lang: 'haxe' }, | |
{ test: /\.md$/, lang: 'markdown' }, | |
{ test: /\.py$/, lang: 'python' }, | |
{ test: /\.rb$/, lang: 'ruby' }, | |
{ test: /\.styl$/, lang: 'stylus' }, | |
{ test: /\.ts$/, lang: 'typescript' }, | |
{ test: /\.yml$/, lang: 'yaml' } | |
] | |
export function highlightCode (filename, content, lang = null) { | |
let language | |
if (lang) { | |
language = { lang } | |
} | |
if (!language) { | |
language = languages.find(l => l.test.test(filename)) | |
} | |
if (!language) { | |
const ext = path.extname(filename).substr(1) | |
if (Prism.languages[ext]) { | |
language = { lang: ext } | |
} | |
} | |
// No language found | |
if (!language) return content | |
// Highlight code | |
return Prism.highlight(content, Prism.languages[language.lang], language.lang) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment