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:
const pluginOrTheme = {
clientAppEnhanceFiles: path.resolve(__dirname, './path/to/clientAppEnhance.ts'),
}
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.
import { defineClientAppEnhance } from '@vuepress/client'
export default defineClientAppEnhance(({ app, router, siteData }) => {
// ...
})
- The
app
is the Vue application instance that created by createAppopen in new window. - The
router
is the Vue Router instance that created by createRouteropen in new window. - The
siteData
is an object that generated from user config, including base, lang, title, description, head and locales.
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 componentopen in new window method:
import { defineClientAppEnhance } from '@vuepress/client'
import MyComponent from './MyComponent.vue'
export default defineClientAppEnhance(({ app, router, siteData }) => {
app.component('MyComponent', MyComponent)
})
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.
import { defineClientAppEnhance } from '@vuepress/client'
export default defineClientAppEnhance(async ({ app, router, siteData }) => {
if (!__SSR__) {
const nonSsrFriendlyModule = await import('non-ssr-friendly-module')
// ...
}
})
Use Router Methods
You can make use of the Router Methodsopen in new window that provided by vue-router. For example, add navigation guard:
import { defineClientAppEnhance } from '@vuepress/client'
export default defineClientAppEnhance(({ app, router, siteData }) => {
router.beforeEach((to) => {
console.log('before navigation')
})
router.afterEach((to) => {
console.log('after navigation')
})
})
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.