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.
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. -
Register Layout Component
Register your
Layout.vueintheme/index.js.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.
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.