prismjs是一款非常好用的代码高亮插件,并且本身也支持皮肤扩展,在页面中展示代码在好不过了。在标准HTML中引入对应的js和css即可使用,在nuxt.js中则需要以下配置
nuxt 版本
"nuxt": "^2.14.0",
prismjs 依赖
cnpm i --save Prismjs
cnpm i --save babel-plugin-prismjs
nuxt.config.js 配置
build: {
babel: {
plugins: [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
], // 这个是是UI配置,不涉及prismjs ,一个多plugins示例
[
'prismjs',
{
languages: [
'html',
'java',
'css',
'ruby',
'javascript',
'sql',
'c',
'docker', // docker
'cpp', // c++
'csharp', // c#
'json', // JSON
'kotlin', // Kotlin
'lua', // lua
'markdown', // markdown
'mongodb', // mongodb
'plsql', // plsql
'markup', // markup
'python',
'go',
],
plugins: [
'line-numbers',
'show-language',
'copy-to-clipboard'
],
theme: 'tomorrow',
css: true
}
]
]
},
// ...
}
配置项中的值可以在node_modules/_prismjs/components.json
中查看
以下情况需要单独额外的配置
// 挂载时触发,针对异步加载的DOM
mounted(){
process.browser && document.querySelectorAll("pre code").forEach(block => Prism.highlightElement(block));
},
// 更新时触发,针对 <nuxt-child>
updated() {
process.browser && document.querySelectorAll("pre code").forEach(block => Prism.highlightElement(block));
}