CodeMirror SSR in VuePress
I have ran into a problem when I started building my VuePress project, which relied on vue-codemirror
to render highlighted code examples. After digging around, I realized that importing codemirror libraries at runtime was not going to work with VuePress, as they reference window
object. So, here is the solution I have come up with.
- Wrap with
ClientOnly
<div class="code">
<ClientOnly>
<codemirror :value="raw" :options="cmOptions"></codemirror>
</ClientOnly>
</div>
2. Replace Vue.use(VueCodeMirror)
Do not use the codemirror Vue plugin in .vuepress/enhanceApp.js
, because it’s the offender that loads the non-SSR scripts. Instead, redefine the component and import the necessary scripts from node_modules
.
Create .vuepress/codemirror.js
module:
Now you can build your VuePress project. Sadly codemirror will be rendered asynchronously. If you want your code to be indexed by search engines, you could possible add an SSR-friendly output, which you can hide, once codemirror is rendered.