Vuepress build error: window is not defined [How to Solve]

1. Problems

When using vuepress to build documents, the following problems occur:

2. Reasons

This is because the static files generated by vuepress build are rendered through the node server. Therefore, there is a problem when the API of the browser/DOM is not accessed in the beforemount or mounted hook in the component.

3. Solutions

For the components introduced in the markdown file (. MD), use the built-in < ClientOnly> component package
for example:

<ClientOnly>
  <NonSSRFriendlyComponent/>
</ClientOnly>

However, the above method can not solve the problem of accessing the browser API by introducing a third-party component library into the component. You can use the on-demand loading function of import provided by ES6. Used in the mounted hook of the component.

<script>
export default {
  mounted () {
  	// The introduced module will be loaded only when the component is mounted
    import('./lib-that-access-window-on-import').then(module => {
      // use code
    })
  }
}
</script>


Read More: