Next新增搜索功能

当文章的数量越来越多时,如果站内有搜索功能,对读者来说会非常的实用

1. 安装搜索插件

1
npm install hexo-generator-search

如果你在网上搜索教程会发现,有些教程安装的是hexo-generator-search插件,有些教程安装的是hexo-generator-searchdb插件,区别在于theme-next/hexo-generator-searchdb 目前为止已经停更

查看一下发现项目属于IVan大佬管辖,众所周知,Ivan大佬管理的theme-next主题也已停止更新,不再活跃,因此才有了后来的Stevenjoezhang管理的next-theme主题,详细见博客内相关博文,话不多说,我们要认准安装的是hexo-generator-search

hexo-generator-search本身在不断的更新,还在支持新的能力

2. 修改主题配置文件

修改主题配置文件_config.next.yml中的local_search

enable: false开启为enable: true

1
2
3
4
5
6
7
8
9
10
11
12
13
# Local Search
# Dependencies: https://github.com/next-theme/hexo-generator-searchdb
local_search:
enable: true
# If auto, trigger search by changing input.
# If manual, trigger search by pressing enter key or search button.
trigger: auto
# Show top n results per article, show all results by setting to -1
top_n_per_article: 1
# Unescape html strings to the readable one.
unescape: false
# Preload the search data when the page loads.
preload: false

到这一步其实基础的搜索功能就可以使用了,且一般不会有问题

3. 其他

大家网上在搜索教程的时候,会发现有些教程还会修改 站点配置文件 _config.yml,在站点配置文件中添加以下内容,大差不差,有的会加更多属性,有的会少加

1
2
3
4
5
search:
path: search.xml
field: post
content: true
template: ./search.xml

这快内容是参考官方配置的,下面是官方的解释:

  • path - file path. By default is search.xml . If the file extension is .json, the output format will be JSON. Otherwise XML format file will be exported.

  • field

    - the search scope you want to search, you can chose:

    • post (Default) - will only covers all the posts of your blog.
    • page - will only covers all the pages of your blog.
    • all - will covers all the posts and pages of your blog.
  • content - whether contains the whole content of each article. If false, the generated results only cover title and other meta info without mainbody. By default is true.

  • template (Optional) - path to a custom XML template

首先解释一下search.xml文件的作用,实际上是由搜索插件整合文章的信息生成的一个用于本地检索的数据库,换句话说为全站所有 post 类型的页面生成结构化的数据,并保存在本站的 /search.xml 当中,借助这个文件,我们就可以实现本地搜索功能

这个文件的生成与否,和站点配置文件是否添加search:选项并无关系,不配置也会生成,因为这就是搜索功能所必需的一个文件

xml文件

就是说站点配置文件可以按需修改,可以添加配置项,也可以不添加,不添加的话默认生成的就是search.xml

4. 可能出现的问题

有的小兄弟在配置搜索功能时会出现无法搜索的问题,大致是这两点问题

  • 搜索插件没有配置好

    搜素插件没有配置好时,按照上述配置方式配置一遍就行,一般没有什么问题

  • 文章中包含特殊字符

    文章中包含特殊字符时,有两个方法,一是将含有特殊字符的文章全部找出来,删去或修改都可以,然后重新hexo g & hexo s,二是将站点配置文件中的search.xml修改为search.json

1
2
3
4
search:
path: search.json
field: post
content: true

json格式比xml格式更加的通用简单,即使含有特殊字符,大概率也不会产生无法搜索的问题,就是采用json格式在搜索时,预览中不会渲染markdown语法,会出现下面这种情况

json问题

当然我还是希望即使是预览,也能正常一点,下面是改成search.yml后的结果

xml显示

参考链接:

  1. Hexo NexT 魔改系列之二
  2. 为 hexo 博客添加本地搜索功能
  3. Hexo 博客无法搜索的终极解决方法