docusaurus中本地搜索,如何使本地搜索支持中文搜索
时间: 2024-01-28 08:04:17 浏览: 30
docusaurus默认使用的是ElasticLunr搜索库,该库本身支持中文搜索,但需要进行一些额外的配置才能正常使用。
首先,在docusaurus项目的根目录下的`docusaurus.config.js`中添加以下配置:
```js
module.exports = {
// ...其他配置
themeConfig: {
// ...其他配置
algolia: {
apiKey: 'YOUR_API_KEY',
indexName: 'YOUR_INDEX_NAME',
// 指定搜索语言为中文
searchParameters: {
'query': '',
'queryType': 'prefixNone',
'restrictSearchableAttributes': [
'title',
'content',
'tags',
'categories'
],
'advancedSyntax': false,
'analytics': false,
'clickAnalytics': false,
'hitsPerPage': 10,
'highlightPreTag': '<mark>',
'highlightPostTag': '</mark>',
'snippetEllipsisText': '...'
}
}
}
}
```
其中,`YOUR_API_KEY`和`YOUR_INDEX_NAME`需要替换成你自己的Algolia搜索服务的API Key和Index Name。
其次,在你的文档页面中,如果使用了本地搜索组件,需要添加以下代码,以支持中文搜索:
```jsx
import React from 'react';
import SearchBar from '@theme/SearchBar';
function LocalSearchBar(props) {
return (
<SearchBar
{...props}
searchParam={{
hitsPerPage: 10,
attributesToRetrieve: ['title', 'content'],
queryType: 'prefixLast',
attributesToSnippet: ['content:20'],
snippetEllipsisText: '...',
restrictSearchableAttributes: ['title', 'content']
}}
/>
);
}
export default LocalSearchBar;
```
在上面的代码中,我们通过设置`queryType`为`prefixLast`,以支持中文搜索。此外,我们还可以设置其他的搜索参数,如`hitsPerPage`、`attributesToRetrieve`、`attributesToSnippet`等。
最后,在你的文档页面中使用刚刚定义的本地搜索组件即可:
```jsx
import LocalSearchBar from './LocalSearchBar';
function MyDoc() {
return (
<div>
<LocalSearchBar />
{/* ...其他内容 */}
</div>
);
}
export default MyDoc;
```
这样就可以在docusaurus中使用本地搜索,并支持中文搜索了。