Import Vue.js Component Into VuePress 1.x: vue-carousel example

May 23, 2019
resolve ReferenceError: window is not defined

I wanted to have a carousel of images (using vue-carousel) on my VuePress page.

Install vue-carousel.

yarn add vue-carousel

NOTE: We cannot import vue-carousel via docs/.vuepress/enchanceApp.js due to build error of ReferenceError: window is not defined. Refer to Build Error.

Create a custom vue component at docs/.vuepress/component/ImageCarousel.vue.

<template>
  <div style="width: 400px; display:block; margin:0 auto;">
    <carousel :per-page="1" :center-mode="true" >
      <slide>
        <img src="https://placeimg.com/400/300/animals" />
      </slide>
      <slide>
        <img src="https://placeimg.com/400/300/nature" />
      </slide>
      <slide>
        <img src="https://placeimg.com/400/300/people" />
      </slide>
    </carousel>
  </div>
</template>

<script>
import { Carousel, Slide } from 'vue-carousel';

export default {
  components: {
    Carousel,
    Slide
  },
  /*
  mounted () {
    import('vue-carousel').then(module => {
      // Vue.use(module);
      // Vue.component('carousel', module.Carousel);
    });
  }
   */
}
</script>

Edit a markdown file to embed the component: docs/README.md

<ClientOnly>
  <ImageCarousel />
</ClientOnly>

You will get the following warning during build (yarn docs:build), but it will work.

Rendering page: /[Vue warn]: Failed to resolve async component: () => Promise.all(/* import() */[__webpack_require__.e(14), __webpack_require__.e(7)]).then(__webpack_require__.bind(null, 244))
Reason: ReferenceError: window is not defined

Build Error

IMPORTANT: This following code doesn’t work during build (yarn docs:build) due to import VueCarousel from 'vue-carousel' with the error ReferenceError: window is not defined due to Browser API Access Restrictions

Edit docs/.vuepress/enchanceApp.js.

import VueCarousel from 'vue-carousel';
// import { Carousel, Slide } from 'vue-carousel';

export default ({
  Vue, // the version of Vue being used in the VuePress app
  options, // the options for the root Vue instance
  router, // the router instance for the app
  siteData // site metadata
}) => {
  // ...apply enhancements to the app
  Vue.use(VueCarousel);
  // Vue.component('carousel', Carousel);
  // Vue.component('slide', Slide);
}

NOTE: I have yet to figure out how to import via @vuepress/plugin-register-components.

Edit docs/README.md

<div style="width: 400px; display:block; margin:0 auto;">
  <carousel :per-page="1" :center-mode="true" >
    <slide>
      <img src="https://placeimg.com/400/300/animals" />
    </slide>
    <slide>
      <img src="https://placeimg.com/400/300/nature" />
    </slide>
    <slide>
      <img src="https://placeimg.com/400/300/people" />
    </slide>
  </carousel>
</div>
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.