CodeMirror SSR in VuePress

Ismayil Khayredinov
1 min readApr 18, 2019

--

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.

  1. 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.

--

--

Ismayil Khayredinov
Ismayil Khayredinov

Written by Ismayil Khayredinov

Software engineer who combines optimism with pessimism to build robust and idiot-proof solutions

Responses (1)