highlight.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Prism don't like cjs with EMS package
  2. // So we use ES modules for the whole file
  3. import Prism from 'prismjs'
  4. import loadLanguages from 'prismjs/components/index.js'
  5. import path from 'path'
  6. loadLanguages()
  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. export function highlightCode (filename, content, lang = null) {
  22. let language
  23. if (lang) {
  24. language = { lang }
  25. }
  26. if (!language) {
  27. language = languages.find(l => l.test.test(filename))
  28. }
  29. if (!language) {
  30. const ext = path.extname(filename).substr(1)
  31. if (Prism.languages[ext]) {
  32. language = { lang: ext }
  33. }
  34. }
  35. // No language found
  36. if (!language) return content
  37. // Highlight code
  38. return Prism.highlight(content, Prism.languages[language.lang], language.lang)
  39. }