VitePress Extending Theme
Creating a completely custom theme from scratch can be complex. In many cases, you may just want to make some adjustments to the default theme or add some new features. VitePress allows you to extend the default theme, which is a simpler and recommended customization approach.
Inheriting Default Theme
To extend the default theme, you need to import it in .vitepress/theme/index.js and export it as the foundation for your custom theme.
// .vitepress/theme/index.js
import DefaultTheme from 'vitepress/theme'
export default {
...DefaultTheme,
// Add your custom logic here
}This way, your theme will inherit all components, styles, and functionality of the default theme.
Using Vue Slots
The default theme's layout component exposes Vue slots at key positions, allowing you to inject custom content or components into specific areas without modifying the theme's source code.
Available Slots
layout-toplayout-bottomnav-bar-title-beforenav-bar-title-afternav-bar-content-beforenav-bar-content-aftersidebar-nav-beforesidebar-nav-afterpage-toppage-bottomdoc-footer-beforedoc-beforedoc-afteraside-topaside-bottom
How to Use
Create Layout Component
Create a layout component in the
.vitepress/themedirectory, such asLayout.vue.vue<!-- .vitepress/theme/Layout.vue --> <script setup> import DefaultTheme from 'vitepress/theme' const { Layout } = DefaultTheme </script> <template> <Layout> <template #doc-after> <div class="my-comment-system"> <h3>Comments</h3> <!-- Integrate your comment system component here --> </div> </template> </Layout> </template> <style> .my-comment-system { margin-top: 2rem; padding: 1rem; border-top: 1px solid var(--vp-c-divider); } </style>Register Layout Component
Register your
Layout.vueintheme/index.js.javascript// .vitepress/theme/index.js import DefaultTheme from 'vitepress/theme' import Layout from './Layout.vue' export default { ...DefaultTheme, Layout: Layout, // Use your custom layout }In this example, we added a comment section at the end of each document content through the
#doc-afterslot. We didn't reinvent the entire layout; we just injected new content on top of the default layout.
Overriding Internal Components
If you want to replace a specific component of the default theme (such as the Logo or navbar search box), you can override it through the enhanceApp function in your theme configuration.
// .vitepress/theme/index.js
import DefaultTheme from 'vitepress/theme'
import MyLogo from './MyLogo.vue'
export default {
...DefaultTheme,
enhanceApp({ app }) {
// Register a global component to override the default VPNavBarTitle
app.component('VPNavBarTitle', MyLogo)
}
}This way, you can replace the default Logo and title area with your own MyLogo.vue component without touching other parts.
Extending the default theme is a powerful way to achieve high customization while maintaining default functionality and appearance.