记录使用VitePress中遇到的各种问题

第一次使用 VitePress 做文档,边开发边记录,是个好习惯!

文档根目录docs,publicPath helpCenter

❤️ 已基本解决的问题

logo配置

logo文件放到 docs/public 文件夹下

配置favicon

js 复制代码
const base = '/helpCenter/'

export default defineConfig({
  head: [['link', { rel: 'icon', href: base + 'favicon.ico' }]],

使用CSS预处理器

VitePress 内置支持 CSS 预处理器:.scss.sass、.less.styl.stylus 文件。无需为它们安装 Vite 专用插件,但必须安装相应的预处理器:

bash 复制代码
# .scss and .sass
npm install -D sass

# .less
npm install -D less

# .styl and .stylus
npm install -D stylus

自动生成侧边栏

js 复制代码
// siderbar.ts

import path from 'path'
import fs from 'fs'

function genSideFiles(file): string[] {
  const list = fs.readdirSync(file)
  let results: string[] = []
  list.forEach((file2: string) => {
    file2 = file + '/' + file2
    if (path.extname(file2) === '.md') results.push(file2.replace('./docs/src', ''))
  })
  return results
}

// 动态生成侧边栏函数
export const walk = function (dir, subDir = '') {
  let results: string[] = []
  const list = fs.readdirSync(dir + subDir)

  list.forEach((file: string) => {
    file = dir + subDir + '/' + file

    const stats = fs.statSync(file)

    // 如果是下级目录
    if (stats.isDirectory()) {
      const list2 = fs.readdirSync(file)

      list2
        .forEach((file2: string) => {
          file2 = file + '/' + file2
          if (path.extname(file2) === '.md') results.push(file2.replace('./docs/src', ''))
        })
        ?.sort((a, b) => {
          const index1 = Number(a.text.split('.')[0])
          const index2 = Number(b.text.split('.')[0])
          return index1 - index2
        })
    }
    // 找到md文件
    if (path.extname(file) === '.md') {
      results.push(file.replace('./docs/src', ''))
    }
  })
  const items = results.map((item) => {
    return {
      text: path.basename(item, '.md'),
      link: item.replace('./docs/src', '').replace('.md', '')
    }
  })

  return {
    text: subDir,
    collapsible: true,
    collapsed: false,
    items: items
  }
}
js 复制代码
// config.mts
 sidebar: [
      {
        text: '常见问题',
        collapsed: false,
        items: [walk(baseDir + '/常见问题', '')]
      }

中文国际化

js 复制代码
// zh.ts
export default {
  outline: { label: '页面导航' },
  docFooter: { prev: '上一页', next: '下一页' }
}

在theme/config.mts中引入

js 复制代码
import zh from "./zh";
export default defineConfig({
  // ...

  themeConfig: {
    // https://vitepress.dev/reference/default-theme-config
    
    ...zh,
    
    // 下面代码是搜索框的中文国际化
    search: {
      provider: "local",
      options: {
        translations: {
          button: {
            buttonText: "搜索帮助中心",
            buttonAriaLabel: "搜索帮助中心",
          },
          modal: {
            noResultsText: "无法找到相关结果",
            resetButtonTitle: "清除查询条件",
            footer: {
              selectText: "选择",
              navigateText: "切换",
              closeText: "关闭",
            },
          },
        },
      },
    },
  },
});

使用 element-plus

安装 element-plus

bash 复制代码
pnpm add element-plus -w

在theme/index.ts中引入

js 复制代码
// https://vitepress.dev/guide/custom-theme
import { h } from 'vue'
import type { Theme } from 'vitepress'
import DefaultTheme from 'vitepress/theme'
import './style.css'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

import Home from './Home.vue'

export default {
  extends: DefaultTheme,

  Layout: () => {
    return h(DefaultTheme.Layout, null, {
      // https://vitepress.dev/guide/extending-default-theme#layout-slots
    })
  },
  // Layout,
  enhanceApp({ app, router, siteData }) {
    // ...
    app.use(ElementPlus)
    app.component('Home', Home)
  }
} satisfies Theme

然后和平常一样使用就好了

html 复制代码
<el-button>click me</el-button>

判断当前环境是否 dev

打印import.meta.env,我们可以在控制台看到

consle 复制代码
{
    "BASE_URL": "/helpCenter/",
    "MODE": "development",
    "DEV": true,
    "PROD": false,
    "SSR": false
}
js 复制代码
if (import.meta.env.DEV) {
  // 当前是 dev
}

增加权限控制/登录后查看

现在的解决办法是判断 localstorage,感觉并不是多好的方法

js 复制代码
const hasToken = localStorage.getItem('token')
if (!hasToken) {
    // 跳转到登录
}

Hydration completed but contains mismatches

当我如以上代码使用localstorage时,本地运行是没问题的。但当我发布到服务器上,Hydration completed but contains mismatches,并且刷新某些文档时,文档内容消失了,但是有的文档是好的。

这好像是碰到 SSR 使用localstorage的问题,然而我对 SSR 的了解几乎为0,只好继续搜索解决办法,还好让我找到了一篇文章www.cnblogs.com/changxue/p/... 加上onMounted顺利解决该问题。

js 复制代码
onMounted(() => {
  const hasToken = window.localStorage.getItem('main_accessToken')
  if (!import.meta.env.DEV) {
    if (!hasToken) window.location.href = 'http://' + location.hostname + '/cloud'
  }
})

🌟 待解决问题

添加图片放大预览效果

相关推荐
hu_nil26 分钟前
Python第七周作业
java·前端·python
溜达哥42 分钟前
git commit 执行报错 sh: -/: invalid option
前端·javascript·git
江梦寻1 小时前
最新Chrome与Selenium完美兼容指南(含驱动下载与配置)
前端·chrome·selenium·测试工具·edge·edge浏览器
Menior_1 小时前
进程地址空间(比特课总结)
前端·chrome
kymjs张涛2 小时前
前沿技术周刊 2025-06-09
android·前端·ios
前端康师傅2 小时前
JavaScript 变量详解
前端·javascript
Sun_light2 小时前
队列:先进先出的线性数据结构及其应用
前端·javascript·算法
Data_Adventure2 小时前
如何在本地测试自己开发的 npm 包
前端·vue.js·svg
萌萌哒草头将军2 小时前
⚓️ Oxlint 1.0 版本发布,比 ESLint 快50 到 100 倍!🚀🚀🚀
前端·javascript·vue.js
ak啊2 小时前
WebGL入门教程:实现场景中相机的视角与位置移动
前端·webgl