Usage of Client App Enhance

The clientAppEnhanceFiles hook of Plugin API allows you to set the path to the client app enhance files. You can use it in your plugin or theme:

  1. const pluginOrTheme = {
  2. clientAppEnhanceFiles: path.resolve(__dirname, './path/to/clientAppEnhance.ts'),
  3. }

Then create a clientAppEnhance.ts file. You can make use of the defineClientAppEnhance helper to get the types hint. Notice that the function can be either synchronous or asynchronous.

  1. import { defineClientAppEnhance } from '@vuepress/client'
  2. export default defineClientAppEnhance(({ app, router, siteData }) => {
  3. // ...
  4. })

The client app enhance will be invoked after the client app is created. It’s possible to implement any enhancements to the Vue application.

TIP

For ease of use in user config, the .vuepress/clientAppEnhance.{js,ts} file will be used as the client app enhance file implicitly, unless you set clientAppEnhanceFiles explicitly in the config file.

Register Vue Components

You can register global Vue components via the componentUsage of Client App Enhance - 图3open in new window method:

  1. import { defineClientAppEnhance } from '@vuepress/client'
  2. import MyComponent from './MyComponent.vue'
  3. export default defineClientAppEnhance(({ app, router, siteData }) => {
  4. app.component('MyComponent', MyComponent)
  5. })

Use Non-SSR-Friendly Features

VuePress will generate a SSR application to pre-render pages during build. Generally speaking, if a code snippet is using Browser / DOM APIs before client app is mounted, we call it non-SSR-friendly.

We already provides a ClientOnly component to wrap non-SSR-friendly content.

In client app enhance files, you can make use of the __SSR__ flag for that purpose.

  1. import { defineClientAppEnhance } from '@vuepress/client'
  2. export default defineClientAppEnhance(async ({ app, router, siteData }) => {
  3. if (!__SSR__) {
  4. const nonSsrFriendlyModule = await import('non-ssr-friendly-module')
  5. // ...
  6. }
  7. })

Use Router Methods

You can make use of the Router MethodsUsage of Client App Enhance - 图4open in new window that provided by vue-router. For example, add navigation guard:

  1. import { defineClientAppEnhance } from '@vuepress/client'
  2. export default defineClientAppEnhance(({ app, router, siteData }) => {
  3. router.beforeEach((to) => {
  4. console.log('before navigation')
  5. })
  6. router.afterEach((to) => {
  7. console.log('after navigation')
  8. })
  9. })

WARNING

It not recommended to use addRoute method to add dynamic routes here, because those routes will NOT be pre-rendered in build mode.

But you can still do that if you understand the drawback.