VitePress使用小结

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

文档根目录docs,publicPath myDocs

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

配置favicon

const base = '/myDocs/'

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

使用CSS预处理器

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

# .scss and .sass
npm install -D sass

# .less
npm install -D less

# .styl and .stylus
npm install -D stylus

自动生成侧边栏

VitePress使用小结
image.png
// 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,
    collapsibletrue,
    collapsedfalse,
    items: items
  }
}

// config.mts
 sidebar: [
      {
        text'常见问题',
        collapsedfalse,
        items: [walk(baseDir + '/常见问题''')]
      }

中文国际化

可配置的国际化字段参考:https://github.com/vuejs/vitepress/blob/main/types/default-theme.d.ts

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

在theme/config.mts中引入

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

pnpm add element-plus -w

在theme/index.ts中引入

// 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

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

<el-button>click me</el-button>

判断当前环境是否 dev

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

{
"BASE_URL": "/myDocs/",
"MODE": "development",
"DEV": true,
"PROD": false,
"SSR": false
}
if (import.meta.env.DEV) {
  // 当前是 dev
}

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

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

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

Hydration completed but contains mismatches

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

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

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


原文始发于微信公众号(自由前端之路):VitePress使用小结

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/258517.html

(0)
葫芦侠五楼的头像葫芦侠五楼

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!