Customize Search for VitePress Project
VitePress includes a robust local search provider that works immediately after activation. You can further enhance the user experience by forcing the search modal to display detailed results with content excerpts by default.
Create the Search Script
To modify the default behavior of the search modal, you must create a separate script file. Navigate to your public assets directory and create a file at docs/public/ts/search.ts.
Add the following line to the file. This code ensures that the detailed list preference is set to true in the user's browser whenever they load your documentation.
// Custom script to enable detailed list by default
localStorage.setItem('vitepress:local-search-detailed-list', 'true');Update Site Configuration
After creating the script, you need to register it in the head section of your configuration file. Open .vitepress/config.ts and add a new entry to the head array. This ensures the script is injected into every page of your site.
export default defineConfig({
title: "My Docs",
head: [
// ... existing head tags
["script", { src: "/ts/search.ts" }]
],
themeConfig: {
search: {
provider: "local"
}
}
})Configuration Logic
VitePress stores search preferences in the browser's local storage. By including this script in the document head, you programmatically set the toggle for the detailed view. This removes the need for users to manually click the detailed view button in the search interface.
| Key | Value | Effect |
|---|---|---|
vitepress:local-search-detailed-list | true | Displays content excerpts in search results by default |
Verify the Customization
Restart your development server to ensure the new configuration is loaded correctly.
npm run docs:devyarn docs:devpnpm docs:devbun run docs:devOnce the site is running, trigger the search modal using the search bar or the shortcut key. Your search results should now appear with descriptive excerpts from the page content immediately. This customization significantly improves discoverability for your readers.
