|
| 1 | +const Prism = require('prismjs') |
| 2 | +const loadLanguages = require('prismjs/components/') |
| 3 | +const path = require('path') |
| 4 | + |
| 5 | +loadLanguages() |
| 6 | + |
| 7 | +const languages = [ |
| 8 | + { test: /\.(html|vue|xml)$/, lang: 'markup' }, |
| 9 | + { test: /\.js$/, lang: 'javascript' }, |
| 10 | + { test: /\.sh$/, lang: 'bash' }, |
| 11 | + { test: /\.coffee$/, lang: 'coffeescript' }, |
| 12 | + { test: /\.gql$/, lang: 'graphql' }, |
| 13 | + { test: /\.hx$/, lang: 'haxe' }, |
| 14 | + { test: /\.md$/, lang: 'markdown' }, |
| 15 | + { test: /\.py$/, lang: 'python' }, |
| 16 | + { test: /\.rb$/, lang: 'ruby' }, |
| 17 | + { test: /\.styl$/, lang: 'stylus' }, |
| 18 | + { test: /\.ts$/, lang: 'typescript' }, |
| 19 | + { test: /\.yml$/, lang: 'yaml' } |
| 20 | +] |
| 21 | + |
| 22 | +exports.highlightCode = function (filename, content, lang = null) { |
| 23 | + let language |
| 24 | + if (lang) { |
| 25 | + language = { lang } |
| 26 | + } |
| 27 | + if (!language) { |
| 28 | + language = languages.find(l => l.test.test(filename)) |
| 29 | + } |
| 30 | + if (!language) { |
| 31 | + const ext = path.extname(filename).substr(1) |
| 32 | + if (Prism.languages[ext]) { |
| 33 | + language = { lang: ext } |
| 34 | + } |
| 35 | + } |
| 36 | + // No language found |
| 37 | + if (!language) return content |
| 38 | + // Highlight code |
| 39 | + return Prism.highlight(content, Prism.languages[language.lang], language.lang) |
| 40 | +} |
0 commit comments