# VitePress文档集合 **Repository Path**: fedocs/vitepress-docs ## Basic Information - **Project Name**: VitePress文档集合 - **Description**: 在VitePress封装中如何封装全局组件 - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: CodeGroup - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 1 - **Created**: 2022-07-19 - **Last Updated**: 2023-09-26 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 前言 `VuePress` 主题默认有 `` 组件用于切换代码很方便。 如图所示: ![image](assets/684615-20220719182811644-1281512504.png) ## 在线体验 http://megasu.gitee.io/vitepress-learn/ ## 痛点 使用 `VitePress` 后,官方没有提供 `` 组件类似的方案。 ## 参考 VuePress 源码 https://github.com/vuejs/vuepress/blob/38e98634af117f83b6a32c8ff42488d91b66f663/packages/%40vuepress/theme-default/global-components/CodeGroup.vue ## 自己封装 CodeGroup 项目下新建全局组件:`components\CodeGroup.vue` 实现代码如下: ```vue ``` ## 全局注册组件 新建主题配置文件:`docs\.vitepress\theme\index.js` `VitePress` 中注册全局组件: ```js import DefaultTheme from 'vitepress/theme' import CodeGroup from '../../../components/CodeGroup.vue' export default { ...DefaultTheme, enhanceApp({ app }) { app.component('CodeGroup', CodeGroup) } } ``` ## 最终效果预览 ![image](assets/684615-20220719183833696-34106808.png) ## 如何在 md 文档中使用 > 🚨注意:由于语法限制,以下代码统一缩进了一个 Tab 制表符,在使用时请删除 Tab 制表符。 ```md # CodeGroup 自定义全局组件 ## 测试 JS + TS
```ts{2} // 注释 const add = (a: number, b: number): number => { return a + b } console.log(add(1, 2)) ```
```js{2} // 注释 const add = (a, b) => { return a + b } console.log(add(1, 2)) ```
## 测试 yarn + npm + pnpm
```sh # install in your project yarn add -D vitePress ```
```sh # install in your project npm install -D vitePress ```
```sh # install in your project pnpm install -D vitePress ```
```