Skip to content

Instantly share code, notes, and snippets.

@lingceng
Created May 28, 2023 10:05
Show Gist options
  • Save lingceng/86422baf67966563031461b83168318a to your computer and use it in GitHub Desktop.
Save lingceng/86422baf67966563031461b83168318a to your computer and use it in GitHub Desktop.
Dynamic import highlight.js language in Rails7
# For code syntax highlight
pin "highlight.js/lib/core", to: "https://ga.jspm.io/npm:[email protected]/lib/core.js"
common_langs = ['xml', 'bash', 'c', 'cpp', 'csharp', 'css', 'markdown', 'diff', 'ruby',
'go', 'graphql', 'ini', 'java', 'javascript', 'json', 'kotlin', 'less',
'lua', 'makefile', 'perl', 'objectivec', 'php', 'php-template', 'plaintext',
'python', 'python-repl', 'r', 'rust', 'scss', 'shell', 'sql', 'swift', 'yaml',
'typescript', 'vbnet', 'wasm']
common_langs.each do |lang|
pin "highlight.js/lib/languages/#{lang}", to: "https://ga.jspm.io/npm:[email protected]/lib/languages/#{lang}.js"
end
import hljs from 'highlight.js/lib/core'
// Help highlight unkown language
import javascript from 'highlight.js/lib/languages/javascript'
hljs.registerLanguage("javascript", javascript)
renderContentOne(markdown) {
let dom = renderMarkdown(markdown) || "<p></p>"
this.contentTarget.innerHTML = dom
this.contentTarget.querySelectorAll('pre code').forEach(function(codeElement) {
const language = Array.from(codeElement.classList).
find(cls => cls.startsWith('language-'))?.replace('language-', '');
// 动态加载需要的语言
if (language && !hljs.getLanguage(language)) {
import('highlight.js/lib/languages/' + language).then((module) => {
hljs.registerLanguage(language, module.default)
hljs.highlightElement(codeElement)
}).catch(err => {
console.warn("highlight error", err)
})
} else {
hljs.highlightElement(codeElement)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment