大家好,我是二哥呀!
不着急的小伙伴可以看看今天的内容哈,给《Java 程序员进阶之路》加了文档搜索,顺带记录一下。如果以后有其他小伙伴在使用过程中也遇到了这个问题,可以参考这篇。
直接来看添加完 docsearch(文档搜索)后的效果,vuepress-theme-hope 会在栏目的右上角添加一个搜索的组件,见下图。
体验网址:https://tobebetterjavaer.com
点击,然后输入想要搜索的内容,就会在弹出框中看到搜索结果,点击可以跳转到对应的网页。
个人感觉还是挺方便和实用的。
至于 Algolia 实现 DocSearch 的原理,也非常的简单,它会根据你的网站内容定时爬虫,当输入关键字的时候就去取之前爬过的内容。
接下来,我来带大家一步步实战。
第一步,通过以下地址提交你的网站和邮箱。
https://docsearch.algolia.com/apply/
第二步,稍安勿躁地等待。邮箱里会收到 docsearch 的验证信息。点击 accept。
PS:发现网页邮箱竟然还是 JSP 做的,这波 666 啊。
第三步,设置 Algolia Crawler,注意替换 recordExtractor。
由于我使用的是 vuepress-theme-hope 主题,所以 recordProps 的默认容器类为 theme-hope-content。
recordProps: {
lvl0: {
selectors: ".sidebar-heading.active",
defaultValue: "Documentation",
},
lvl1: ".theme-hope-content h1",
lvl2: ".theme-hope-content h2",
lvl3: ".theme-hope-content h3",
lvl4: ".theme-hope-content h4",
lvl5: ".theme-hope-content h5",
lvl6: ".theme-hope-content h6",
content: ".theme-hope-content p, .theme-hope-content li",
},
indexHeadings: true,
这部分如果不替换的,DocSearch 是无法搜索到内容的。
另外,记住 indexName、appId、apiKey,它们的值会在接下来配置 vuepress-theme-hope 主题的 DocSearch 插件用到。
第四步,在 themeConfig.ts 文件中配置 docsearch,启用文档搜索。
docsearch: {
appId: "yours",
apiKey: "yours",
indexName: "tobebetterjavaer(yours)",
locales: {
"/": {
placeholder: "搜索文档",
translations: {
button: {
buttonText: "搜索文档",
buttonAriaLabel: "搜索文档",
},
modal: {
searchBox: {
resetButtonTitle: "清除查询条件",
resetButtonAriaLabel: "清除查询条件",
cancelButtonText: "取消",
cancelButtonAriaLabel: "取消",
},
startScreen: {
recentSearchesTitle: "搜索历史",
noRecentSearchesText: "没有搜索历史",
saveRecentSearchButtonTitle: "保存至搜索历史",
removeRecentSearchButtonTitle: "从搜索历史中移除",
favoriteSearchesTitle: "收藏",
removeFavoriteSearchButtonTitle: "从收藏中移除",
},
errorScreen: {
titleText: "无法获取结果",
helpText: "你可能需要检查你的网络连接",
},
footer: {
selectText: "选择",
navigateText: "切换",
closeText: "关闭",
searchByText: "搜索提供者",
},
noResultsScreen: {
noResultsText: "无法找到相关结果",
suggestedQueryText: "你可以尝试查询",
openIssueText: "你认为该查询应该有结果?",
openIssueLinkText: "点击反馈",
},
},
},
},
},
},
第五步,先执行 yarn add @docsearch/js@3
命令添加 docsearch 安装包,再执行 npm i -D @vuepress/plugin-docsearch@next
命令添加插件。
折腾这点折腾了很久,因为两个官网都没有给出比较全的解决方案,导致我摸索了好久,两个都执行了,就不会编译失败了。
否则会报 plugin-docsearch@next 插件没安装,和缺少包。
文档可以参考:
因为《Java 程序员进阶之路》这个小破站,vuepress-theme-hope主题的作者还跑过来加了好友(一开始是好朋友 JavaGuide 推荐了这个主题,然后 hope 的作者还把我俩的网站加到了案例里作为榜样)。
没想到,Hope 说自己“是个学理论物理的小菜鸡”,只能说,作者们都非常谦虚。