Skip to content

Instantly share code, notes, and snippets.

@Akryum
Created May 2, 2019 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Akryum/2985328af5f47b7d3b79900390bd2e4f to your computer and use it in GitHub Desktop.
Save Akryum/2985328af5f47b7d3b79900390bd2e4f to your computer and use it in GitHub Desktop.
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