### Configure Dumi Setup in package.json
Source: https://github.com/umijs/dumi/blob/master/docs/guide/commands.md
Set up the `dumi setup` command to run automatically during package installation by adding it to the `scripts.prepare` section in your `package.json`. This ensures temporary files are generated as needed.
```json
{
"scripts": {
"prepare": "dumi setup"
}
}
```
--------------------------------
### Dumi CLI Commands
Source: https://context7.com/umijs/dumi/llms.txt
Dumi provides CLI commands for development and deployment. Use 'dev' to start the local server, 'build' to create a production build, 'preview' to test the production build locally, 'setup' to generate temporary files (recommended for 'prepare' script), and 'version' to check the installed version.
```bash
# Start local development server with HMR
npx dumi dev
```
```bash
# Build the documentation site for production
npx dumi build
# Output: docs-dist/
```
```bash
# Preview the production build locally
npx dumi preview
npx dumi preview --port 9527
# → Serves docs-dist/ at http://127.0.0.1:9527
```
```bash
# Generate dumi temporary files (run once after install)
# Recommended: add to package.json "prepare" script
npx dumi setup
# package.json example:
# { "scripts": { "prepare": "dumi setup" } }
```
```bash
# Print installed dumi version
npx dumi version
```
--------------------------------
### Package Installation with Tabbed Code Groups
Source: https://context7.com/umijs/dumi/llms.txt
Provides examples for installing a component library using npm, yarn, and pnpm, presented in tabbed code groups.
```bash
npm install my-component-lib
```
```bash
yarn add my-component-lib
```
```bash
pnpm add my-component-lib
```
--------------------------------
### Install Vue and Preset Plugin
Source: https://github.com/umijs/dumi/blob/master/docs/guide/vue.md
Install Vue 3 and the dumi Vue preset plugin using pnpm.
```bash
pnpm i vue
pnpm i -D @dumijs/preset-vue
```
--------------------------------
### Install @dumijs/preset-vue
Source: https://github.com/umijs/dumi/blob/master/suites/preset-vue/README.md
Install the preset using npm.
```bash
npm i @dumijs/preset-vue
```
--------------------------------
### Install @dumijs/vue-meta
Source: https://github.com/umijs/dumi/blob/master/suites/dumi-vue-meta/README.md
Install the package using pnpm.
```bash
pnpm i @dumijs/vue-meta
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/umijs/dumi/blob/master/CONTRIBUTING.md
Install all project dependencies using PNPM. A network proxy may be required if installation fails due to network issues.
```shell
pnpm install
```
--------------------------------
### Start Development Server
Source: https://github.com/umijs/dumi/blob/master/CONTRIBUTING.md
Start the development server for Dumi or its documentation. These commands are used to run the project locally during development.
```shell
pnpm dev
pnpm docs:dev
```
--------------------------------
### Run development and build commands
Source: https://github.com/umijs/dumi/blob/master/suites/father-plugin/README.md
Use these commands to start the development server or build the theme package.
```bash
npm run dev
npm run build
```
--------------------------------
### Vue SFC with Script Setup (Composition API)
Source: https://github.com/umijs/dumi/blob/master/examples/vue/src/Foo/index.md
Demonstrates a Vue SFC using the script setup syntax with TypeScript. It includes reactive state management with `ref` and dynamic styling using `v-bind`.
```vue
{{ msg }}
```
--------------------------------
### Scaffold a New Dumi Project
Source: https://context7.com/umijs/dumi/llms.txt
Bootstrap a new dumi project using the official create-dumi scaffolding tool. Choose from various templates like Static Site, React Library, Vue Library, or Theme Package. After scaffolding, install dependencies and start the development server.
```bash
mkdir my-component-lib && cd my-component-lib
npx create-dumi
# Prompts:
# ? Pick template type
# ❯ Static Site – plain documentation website
# React Library – component library with demos
# Vue Library – Vue component library with demos
# Theme Package – custom dumi theme development
# Install dependencies and start the dev server
npm install
npm start
# → Starts dev server at http://localhost:8000
```
--------------------------------
### Foo Component Work Example
Source: https://github.com/umijs/dumi/blob/master/examples/normal/src/Foo/index.md
Example demonstrating the work functionality of the Foo component. This snippet is loaded from an external file.
```typescript
示例框
```
--------------------------------
### Clone and Setup Dumi Repository
Source: https://github.com/umijs/dumi/blob/master/CONTRIBUTING.md
Clone the Dumi repository and navigate into the project directory. Ensure you have forked the repository first.
```shell
git clone https://github.com//dumi.git
cd dumi
```
--------------------------------
### Include Example: foo.jsx
Source: https://github.com/umijs/dumi/blob/master/src/loaders/markdown/transformer/fixtures/skip-only/case05/index.md
This code block is included by default.
```jsx
import React from 'react';
export default () =>
foo
;
```
--------------------------------
### Install father-plugin-dumi-theme
Source: https://github.com/umijs/dumi/blob/master/suites/father-plugin/README.md
Install this plugin in your devDependencies if you are not using create-dumi.
```bash
npm i father-plugin-dumi-theme -D
```
--------------------------------
### Basic Component Demo
Source: https://context7.com/umijs/dumi/llms.txt
A simple example of a React component used as a demo. Dumi renders this directly.
```APIDOC
## Basic Usage
```jsx
import { Button } from 'my-component-lib';
export default () => (
);
```
```
--------------------------------
### Basic Foo Component
Source: https://github.com/umijs/dumi/blob/master/examples/mobile/src/Foo/index.md
A basic example of the Foo component without any specific configurations.
```jsx
export default () => 'Hello Foo12313121!';
```
--------------------------------
### Install dumi with npm, yarn, or pnpm
Source: https://github.com/umijs/dumi/blob/master/src/loaders/markdown/transformer/fixtures/code-group/index.md
Use the appropriate command for your package manager to install dumi as a development dependency.
```npm
npm install -D dumi
```
```yarn
yarn add -D dumi
```
```pnpm
pnpm add -D dumi
```
--------------------------------
### Include Example: foo.jsx
Source: https://github.com/umijs/dumi/blob/master/src/loaders/markdown/transformer/fixtures/skip-only/case04/index.md
This code snippet is included by default as it does not have the 'only' attribute.
```jsx
import React from 'react';
export default () => {
return (
Hello from foo.jsx
);
};
```
--------------------------------
### Opening Demo in CodeSandbox with openCodeSandbox
Source: https://context7.com/umijs/dumi/llms.txt
Provides an example of creating a custom action button that opens a demo in CodeSandbox using the `openCodeSandbox` utility.
```tsx
// openCodeSandbox — open a demo in CodeSandbox from a custom action button
import { openCodeSandbox } from 'dumi';
import DumiPreviewerActions from 'dumi/theme-default/slots/PreviewerActions';
const PreviewerActions: typeof DumiPreviewerActions = (props) => (
);
export default PreviewerActions;
```
--------------------------------
### Using API Component in Markdown
Source: https://context7.com/umijs/dumi/llms.txt
Markdown example demonstrating how to use the `` component to render an API table for a specific component, identified by its ID.
```md
## API
```
--------------------------------
### Create a new dumi theme package
Source: https://github.com/umijs/dumi/blob/master/suites/father-plugin/README.md
Use create-dumi to start a new dumi theme package. This plugin is included by default in the theme template.
```bash
npx create-dumi # then select `theme`
```
--------------------------------
### Configure Code Block Demo with FrontMatter
Source: https://github.com/umijs/dumi/blob/master/docs/config/demo.md
Use FrontMatter to configure code block demos. This example shows how to set a title for the demo.
```jsx
/**
t * title: demo 标题
*/
import React from 'react';
export default () => <>Hello world!>;
```
--------------------------------
### Render All Code Snippets
Source: https://github.com/umijs/dumi/blob/master/src/loaders/markdown/transformer/fixtures/skip-only/case01/index.md
This snippet includes all code examples without any specific filtering.
```jsx
```
```jsx
```
```jsx
```
--------------------------------
### Basic Button Usage
Source: https://context7.com/umijs/dumi/llms.txt
Renders a primary button that triggers an alert on click. Ensure 'my-component-lib' is installed.
```jsx
import { Button } from 'my-component-lib';
export default () => (
);
```
--------------------------------
### Dumi Plugin API Example
Source: https://context7.com/umijs/dumi/llms.txt
Demonstrates how to use the Dumi Plugin API to add content tabs, hook into build events, modify asset metadata, and customize theme resolution.
```typescript
// my-dumi-plugin/index.ts
import type { IApi } from 'dumi';
export default (api: IApi) => {
// ── Add a content Tab to all component pages ──────────────────────
api.addContentTab(() => ({
key: 'playground',
title: 'Playground',
// Only activate on /components/* routes
test: /\/components\//,
component: require.resolve('./PlaygroundTab'),
}));
// ── Read asset metadata after build ────────────────────────────────
api.onBuildComplete(async () => {
const assets = await api.getAssetsMetadata();
console.log('Total components:', Object.keys(assets.atoms).length);
});
// ── Modify asset metadata before it is written to assets.json ──────
// (triggered by: dumi build --assets)
api.modifyAssetsMetadata((data) => {
data.name = 'My Awesome Library';
data.version = '2.0.0';
return data;
});
// ── Modify theme resolution (components, locales, slots, layouts) ──
api.modifyTheme((memo) => {
// Add extra i18n keys
memo.locales['zh-CN']['custom.greeting'] = '你好';
memo.locales['en-US']['custom.greeting'] = 'Hello';
return memo;
});
};
```
--------------------------------
### Rendered Global Component Example
Source: https://github.com/umijs/dumi/blob/master/docs/theme/global-component.md
This is how the global component will be rendered in the dumi development environment.
```jsx
import React from 'react';
export default () =>
当前 barValue 属性值为:Big Bar!
;
```
--------------------------------
### GitHub Actions 自动部署配置
Source: https://github.com/umijs/dumi/blob/master/docs/guide/faq.md
使用 GitHub Actions 在每次 main 分支更新后自动部署文档到 GitHub Pages。需要配置 checkout, npm install, build 和 deploy 步骤。
```yaml
name: github pages
on:
push:
branches:
- main # default branch
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
# 如果配置 themeConfig.lastUpdated 为 false,则不需要添加该参数以加快检出速度
fetch-depth: 0
- name: Install dependencies
run: npm install
- name: Build with dumi
# 文档编译命令,如果是 react 模板需要修改为 npm run docs:build
run: npm run build
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
# 文档目录,如果是 react 模板需要修改为 docs-dist
publish_dir: ./dist
```
--------------------------------
### usePrefersColor
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Gets and sets the site's theme color (light or dark). Useful for theme switching.
```APIDOC
## usePrefersColor
### Description
Hook to get and set the preferred color scheme (theme) of the site. It can be used to control the theme of component demos or implement a site-wide theme switcher.
### Usage
```typescript
import { usePrefersColor } from 'dumi';
const ThemeSwitcher = () => {
const [color, prefersColor, setPrefersColor] = usePrefersColor();
// 'color' is the currently applied theme ('dark' or 'light')
// 'prefersColor' is the user's preference ('dark', 'light', or 'auto')
// 'setPrefersColor' is a function to update the preference
const handleThemeChange = (theme: 'dark' | 'light' | 'auto') => {
setPrefersColor(theme);
};
return (
Current theme: {color}
);
};
```
### Return Value
Returns a tuple containing:
1. `color`: The currently active theme ('dark' or 'light').
2. `prefersColor`: The user's preferred theme setting ('dark', 'light', or 'auto').
3. `setPrefersColor`: A function to update the user's preferred theme setting.
```
--------------------------------
### Exporting Public Components from Index
Source: https://context7.com/umijs/dumi/llms.txt
An example of an index file that exports all public components, intended for use with Dumi's API parser.
```tsx
// src/index.ts — export all public components
export { Button } from './Button';
export { Modal } from './Modal';
```
--------------------------------
### Hello World React Component
Source: https://github.com/umijs/dumi/blob/master/examples/normal/docs/index.md
A basic React component that renders a "Hello first code block demo!" message. This is a standard functional component suitable for initial setup.
```jsx
import React from 'react';
export default () => <>Hello first code block demo!>;
```
--------------------------------
### Handling SFC Compilation in onBlockLoad
Source: https://github.com/umijs/dumi/blob/master/docs/plugin/techstack.md
Implement the onBlockLoad method to take over default dependency analysis for non-JS/TS files like .vue. This example shows how to compile SFCs and return the processed content.
```typescript
onBlockLoad(
args: IDumiTechStackOnBlockLoadArgs,
): IDumiTechStackOnBlockLoadResult {
const result = compileSFC({
id: args.path,
code: args.entryPointCode,
filename: args.filename,
});
return {
type: 'tsx',
content: Array.isArray(result) ? '' : result.js,
};
}
```
--------------------------------
### Define Vue SFC Tech Stack with defineTechStack
Source: https://github.com/umijs/dumi/blob/master/docs/plugin/techstack.md
Implement the IDumiTechStack interface using defineTechStack to add Vue SFC support. This example shows the basic structure and key methods.
```typescript
import { defineTechStack, wrapDemoWithFn } from 'dumi/tech-stack-utils';
import { logger } from 'dumi/plugin-utils';
export const VueSfcTechStack = defineTechStack({
name: 'vue3-sfc',
runtimeOpts: {},
isSupported(_, lang: string) {
return ['vue'].includes(lang);
},
onBlockLoad(args) {
// ...
},
transformCode(raw, opts) {
if (opts.type === 'code-block') {
const js = '...';
const code = wrapDemoWithFn(js, {
filename,
parserConfig: { syntax: 'ecmascript' },
});
return `(${code})()`;
}
return raw;
},
});
api.registerTechStack(() => VueSfcTechStack);
```
--------------------------------
### Invalid React Component Example
Source: https://github.com/umijs/dumi/blob/master/src/loaders/markdown/transformer/fixtures/react-component/index.md
Represents an example of an invalid or self-closing component tag.
```jsx
```
--------------------------------
### Component Demo with FrontMatter Options
Source: https://context7.com/umijs/dumi/llms.txt
Demonstrates how to use FrontMatter to configure demo appearance and behavior, such as background color and default code visibility.
```APIDOC
## With Custom Background (demo FrontMatter options)
```jsx
/**
* title: Dark Background Example
* description: Rendered on a dark background to show contrast.
* background: '#1a1a1a'
* compact: false
* defaultShowCode: true
* transform: true
*/
import { Button } from 'my-component-lib';
export default () => ;
```
```
--------------------------------
### Create Global Component Files
Source: https://github.com/umijs/dumi/blob/master/docs/theme/global-component.md
Create the necessary directory and file for your global component within your local theme or theme package.
```bash
# In local theme
$ mkdir -p .dumi/theme/builtins
$ touch .dumi/theme/builtins/Foo.tsx
# In theme package
$ touch src/builtins/Foo.tsx
```
--------------------------------
### Initialize Plugin Project with Father
Source: https://github.com/umijs/dumi/blob/master/docs/plugin/new.md
Use the create-father command to scaffold a new plugin project. Choose the target platform (Node.js or Both) based on your plugin's requirements.
```bash
npx create-father
```
--------------------------------
### useLocale
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Gets the current internationalization (i18n) locale data.
```APIDOC
## useLocale
### Description
Hook to access the current internationalization (i18n) locale data for the application. This is useful for implementing features that depend on the user's selected language.
### Usage
```typescript
import { useLocale } from 'dumi';
const LocaleDisplay = () => {
const locale = useLocale();
// 'locale' will be an object like { id: string; name: string; base: string; } or { id: string; name: string; suffix: string }
console.log(locale);
};
```
### Return Value
Returns an object representing the current locale, which can be either `{ id: string; name: string; base: string; }` or `{ id: string; name: string; suffix: string }`.
```
--------------------------------
### Clean and Re-initialize Project Template
Source: https://github.com/umijs/dumi/blob/master/docs/guide/upgrading.md
Use this command sequence to clear your current working directory and re-initialize with create-dumi, then restore your original source and docs.
```bash
$ git rm -rf ./* # 清空现有仓库文件(仅工作区清空,文件仍受 Git 版本控制)
$ npx create-dumi # 然后选择需要的模板
$ rm -rf docs src # 删除初始化模板的 docs 及 src
$ git checkout src docs # 恢复原有的源码及文档
```
--------------------------------
### Only Example: baz.jsx
Source: https://github.com/umijs/dumi/blob/master/src/loaders/markdown/transformer/fixtures/skip-only/case05/index.md
This code block is rendered exclusively due to the 'only' attribute.
```jsx
import React from 'react';
export default () =>
baz
;
```
--------------------------------
### Skip Example: bar.jsx
Source: https://github.com/umijs/dumi/blob/master/src/loaders/markdown/transformer/fixtures/skip-only/case05/index.md
This code block is skipped during rendering due to the 'skip' attribute.
```jsx
import React from 'react';
export default () =>
bar
;
```
--------------------------------
### Preview Dumi Build with Custom Port
Source: https://github.com/umijs/dumi/blob/master/docs/guide/commands.md
Use the `--port` argument with the `dumi preview` command to specify a custom port for the local static web server. This allows you to preview your built documentation on a different port than the default.
```bash
dumi preview --port 9527
```
--------------------------------
### Foo with Title and Description
Source: https://github.com/umijs/dumi/blob/master/examples/mobile/src/Foo/index.md
Use this snippet when you need to display a title, description, and apply a background color with a compact layout.
```jsx
/**
* title: 有标题
* description: 有简介,且有背景色 + 紧凑模式
* compact: true
* background: '#f7f9fb'
*/
export default () => 'Hello Foo!';
```
--------------------------------
### Basic React Component Usage
Source: https://github.com/umijs/dumi/blob/master/src/loaders/markdown/transformer/fixtures/react-component/index.md
Illustrates the basic syntax for rendering a custom React component with props.
```jsx
```
--------------------------------
### Skip Example: baz.jsx
Source: https://github.com/umijs/dumi/blob/master/src/loaders/markdown/transformer/fixtures/skip-only/case04/index.md
Similar to bar.jsx, this snippet is also skipped by default due to the 'only' attribute.
```jsx
import React from 'react';
export default () => {
return (
Hello from baz.jsx
);
};
```
--------------------------------
### Switch High-Definition Solution by Screen Width
Source: https://github.com/umijs/dumi/blob/master/docs/theme/mobile.md
Configure responsive high-definition solutions using 'hd.rules' with 'maxWidth' and 'minWidth' to adapt to different screen sizes.
```typescript
export default {
themeConfig: {
hd: {
rules: [
{ maxWidth: 375, mode: 'vw', options: [100, 750] },
{ minWidth: 376, maxWidth: 750, mode: 'vw', options: [100, 1500] },
],
},
},
};
```
--------------------------------
### Skip Example: bar.jsx
Source: https://github.com/umijs/dumi/blob/master/src/loaders/markdown/transformer/fixtures/skip-only/case04/index.md
This code snippet is skipped by default because it has the 'only' attribute, indicating it should not be rendered unless explicitly targeted.
```jsx
import React from 'react';
export default () => {
return (
Hello from bar.jsx
);
};
```
--------------------------------
### Create Project by JSON Configuration
Source: https://github.com/umijs/dumi/blob/master/suites/dumi-vue-meta/README.md
Create a component metadata checker by providing a JSON configuration object.
```typescript
export declare function createProjectByJson(
options: CheckerProjectJsonOptions,
): Project;
```
--------------------------------
### Get Current Locale Data
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Fetch the current internationalization language data using `useLocale`. This is essential for implementing locale-specific features.
```typescript
import { useLocale } from 'dumi';
const Example = () => {
const locale = useLocale();
// 返回值:{ id: string; name: string; base: string } | { id: string; name: string; suffix: string }
// 类型定义:https://github.com/umijs/dumi/blob/master/src/client/theme-api/types.ts#L152
// 其他逻辑
};
```
--------------------------------
### Create and Use Vue Meta Project
Source: https://github.com/umijs/dumi/blob/master/suites/dumi-vue-meta/README.md
Create a project instance using createProject and extract component library metadata. The extracted metadata includes components and reusable types.
```typescript
import { createProject } from '@dumijs/vue-meta';
import * as path from 'path';
const projectRoot = '';
const project = createProject({
rootPath: projectRoot,
// If tsconfigPath is not set, tsconfig will be /tsconfig.json
tsconfigPath: path.resolve(projectRoot, './tsconfig.json');
});
const entry = path.resolve(projectRoot, './src/index.ts');
const meta = project.service.getComponentLibraryMeta(entry);
meta.components['Button'];
// Reusable types, queried and referenced through `ref`
// (`ref` is the md5 value calculated from the name of the file where the type is located and its type name.)
meta.types;
```
--------------------------------
### Button Component with JSDoc Annotations
Source: https://context7.com/umijs/dumi/llms.txt
Example of a React Button component with JSDoc annotations for its props, which Dumi uses to generate the API table.
```APIDOC
```tsx
// src/Button/index.tsx — JSDoc-annotated props
import React, { type FC } from 'react';
export interface ButtonProps {
/**
* @description Button visual style variant
* @default "default"
*/
type?: 'default' | 'primary' | 'ghost' | 'danger';
/**
* @description Disables the button and prevents interaction
* @default false
*/
disabled?: boolean;
/**
* @description Click event handler
*/
onClick?: (event: React.MouseEvent) => void;
children?: React.ReactNode;
}
export const Button: FC = ({ type = 'default', disabled = false, onClick, children }) => (
);
```
```
--------------------------------
### Configure Homepage Features
Source: https://github.com/umijs/dumi/blob/master/docs/theme/default.md
Use this configuration to display component library features on the homepage in a grid of three items per row. Supports HTML text in descriptions.
```yaml
features:
- emoji: 🚀
title: 性能强大
link: 可为标题配置超链接
description: 可以配置 HTML 文本
```
--------------------------------
### 在 CRA 项目中使用 dumi 添加文档目录和文件
Source: https://github.com/umijs/dumi/blob/master/docs/guide/faq.md
在配置的 APP_ROOT 目录下创建 docs 目录和 index.md 文件来编写文档。
```markdown
# 这是一个 dumi 结合 create-react-app 的 Demo
```
--------------------------------
### Get Matched Route Data
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Retrieve the currently matched route data using `useMatchedRoute`. Can be combined with `getRouteMetaById` for custom metadata retrieval.
```typescript
import { useMatchedRoute, getRouteMetaById, type IRouteMeta } from 'dumi';
import useSWR from 'swr';
export function useMeta() {
const route = useMatchedRoute();
useSWR(route.id, getRouteMetaById, {
onSuccess: (meta: IRouteMeta) => {
// do something with meta
globalThis.console.log(meta);
},
});
}
```
--------------------------------
### Configure Homepage Hero and Features
Source: https://github.com/umijs/dumi/blob/master/docs/guide/page-config.md
Use FrontMatter to define the hero section with a title, description, and actions, and the features section with individual item details for a component library homepage.
```markdown
---
hero:
title: dumi
description: 企业级前端开发框架
actions:
- text: 快速上手
link: /hello
- text: GitHub
link: /hello
features:
- title: 非常快
emoji: 🚀
description: 考究的默认配置和约定式的目录结构,帮助开发者零成本上手,让所有注意力都能放在文档编写和组件开发上
---
```
--------------------------------
### Create Project with Options
Source: https://github.com/umijs/dumi/blob/master/suites/dumi-vue-meta/README.md
Create a meta checker for a Vue project by passing options, including rootPath, tsconfigPath, and checkerOptions. If neither rootPath nor tsconfigPath is set, rootPath defaults to process.cwd().
```typescript
import { createProject } from '@dumijs/vue-meta';
// Manually pass in the tsconfig.json path
createProject({
// If neither rootPath nor tsconfigPath is set, rootPath will be process.cwd()
rootPath: '',
// If tsconfigPath is not set, tsconfig will be /tsconfig.json
tsconfigPath: '/tsconfig.json',
checkerOptions: {},
});
```
--------------------------------
### Get Assets Metadata with getAssetsMetadata
Source: https://github.com/umijs/dumi/blob/master/docs/plugin/api.md
Retrieve the project's asset metadata within the `onBuildComplete` hook. This is useful for further processing or integration with other plugins.
```typescript
api.onBuildComplete(async () => {
const data = await api.getAssetsMetadata();
// do something
});
```
--------------------------------
### Get Current Route Metadata
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Fetch metadata for the current route using `useRouteMeta`. Useful for customizing page features like TOC or Tabs.
```typescript
import { useRouteMeta } from 'dumi';
const Example = () => {
const {
// Markdown/React 的 frontmatter
frontmatter,
// 页面标题数据
toc,
// 页面文本数据
texts,
// 页面 Tab 数据
tabs,
} = useRouteMeta();
// 返回值:IRouteMeta
// 类型定义:https://github.com/umijs/dumi/blob/master/src/client/theme-api/types.ts#L56
// 其他逻辑
};
```
--------------------------------
### Get Full Sidebar Data
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Retrieve all sidebar data across all paths using `useFullSidebarData`. Use `useSidebarData` for the current path's sidebar.
```typescript
import { useFullSidebarData } from 'dumi';
const Example = () => {
const sidebar = useFullSidebarData();
// 返回值:Record
// 类型定义:https://github.com/umijs/dumi/blob/master/src/client/theme-api/types.ts#L171
// 其他逻辑
};
```
--------------------------------
### 创建文件树
Source: https://github.com/umijs/dumi/blob/master/docs/guide/markdown.md
Tree 组件用于创建文件树结构,支持为节点添加注释内容。
```markdown
src
directory
index.md
package.json
```
```diff
src
这是 src 文件夹
directory
没有子项的文件夹
index.md
这是 index.md
package.json
这是 package.json
```
--------------------------------
### Configure External Demo with Code Tag Attributes
Source: https://github.com/umijs/dumi/blob/master/docs/config/demo.md
Configure external demos using attributes on the `code` tag. This allows setting the source, description, and title for an external demo file.
```md
demo 标题
```
--------------------------------
### 将 dumi 临时文件添加到 .gitignore
Source: https://github.com/umijs/dumi/blob/master/docs/guide/faq.md
将 dumi 生成的临时文件添加到 .gitignore 中,避免提交不必要的文件。
```text
.dumi/tmp*
```
--------------------------------
### External Vue SFC Demo
Source: https://github.com/umijs/dumi/blob/master/examples/vue/src/Foo/index.md
Loads an external Vue SFC demo component from a specified path. This is useful for showcasing complex examples or reusable components.
```vue
```
--------------------------------
### Basic Foo Component
Source: https://github.com/umijs/dumi/blob/master/examples/normal/src/Foo/index.md
A simple React component that renders 'Hello Foo!'. No specific imports are needed beyond React itself.
```jsx
import React from 'react';
export default () =>
Hello Foo!
;
```
--------------------------------
### Get Sidebar Data with useSidebarData
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Use this hook to retrieve sidebar data for the current path. It's useful when customizing the sidebar's appearance or behavior.
```typescript
import { useSidebarData } from 'dumi';
const Example = () => {
const sidebar = useSidebarData();
// 返回值:ISidebarGroup[]
// 类型定义:https://github.com/umijs/dumi/blob/master/src/client/theme-api/types.ts#L171
// 其他逻辑
};
```
--------------------------------
### Render Demos with IDs in Columns
Source: https://github.com/umijs/dumi/blob/master/docs/guide/page-config.md
Demos with unique IDs can also be rendered in the configured column layout.
```html
分栏 1分栏 2分栏 3分栏 4
```
--------------------------------
### Get Navigation Bar Data
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Access navigation bar data using `useNavData`. Recommended for customizing navigation components, especially with support for secondary navigation.
```typescript
import { useNavData } from 'dumi';
const Example = () => {
const nav = useNavData();
// 返回值:INavItem[]
// 类型定义:https://github.com/umijs/dumi/blob/master/src/client/theme-api/types.ts#L157
// 其他逻辑
};
```
--------------------------------
### 在 CRA 项目中使用 dumi 安装依赖
Source: https://github.com/umijs/dumi/blob/master/docs/guide/faq.md
在 create-react-app 等非 umi 项目中使用 dumi 时,需要先安装 dumi 和 cross-env 依赖。
```bash
yarn add dumi cross-env -D
```
--------------------------------
### Get All Atom Assets Metadata
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Use `useAtomAssets` to retrieve metadata for all atomic assets. This is helpful for creating asset index pages or customizing API tables.
```typescript
import { useAtomAssets } from 'dumi';
const Example = () => {
const assets = useAtomAssets();
// 返回值:Record
// 类型定义:https://github.com/umijs/dumi/tree/master/assets-types/typings/atom/index.d.ts#L37
// 其他逻辑
};
```
--------------------------------
### Getting Temporary File Path
Source: https://github.com/umijs/dumi/blob/master/docs/plugin/techstack.md
A helper function to construct the absolute path to temporary files generated by dumi, ensuring correct referencing of runtime assets.
```typescript
function getPluginPath(api: IApi, filename: string) {
return winPath(
join(api.paths.absTmpPath, `plugin-${api.plugin.key}`, filename),
);
}
const rendererPath = getPluginPath(api, 'renderer.mjs');
```
--------------------------------
### createProject() - Options
Source: https://github.com/umijs/dumi/blob/master/suites/dumi-vue-meta/README.md
Creates a meta checker for a Vue project by providing options, including root path and tsconfig path.
```APIDOC
## createProject()
### Description
Create a meta checker for Vue project by options
### Type
```typescript
export declare function createProject(options: CheckerProjectOptions): Project;
```
### Parameters
- `options` [**_CheckerProjectOptions_**](#) - An object containing configuration options for the checker.
### Returns
- [`Project`](#) - The created Project instance.
### Examples
```ts
import { createProject } from '@dumijs/vue-meta';
// Manually pass in the tsconfig.json path
createProject({
// If neither rootPath nor tsconfigPath is set, rootPath will be process.cwd()
rootPath: '',
// If tsconfigPath is not set, tsconfig will be /tsconfig.json
tsconfigPath: '/tsconfig.json',
checkerOptions: {},
});
```
```
--------------------------------
### Configure Entry File for API Parsing
Source: https://github.com/umijs/dumi/blob/master/docs/guide/vue-api-table.md
Set the entryFile in dumi's configuration to specify where API parsing should begin.
```typescript
import {
defineConfig
} from 'dumi';
export default defineConfig({
resolve: {
// 配置入口文件路径,API 解析将从这里开始
entryFile: './src/index.ts',
},
});
```
--------------------------------
### Button with Dark Background
Source: https://context7.com/umijs/dumi/llms.txt
Demonstrates rendering a ghost button on a dark background for contrast. This example uses FrontMatter options to set the background color and other display properties.
```jsx
/**
* title: Dark Background Example
* description: Rendered on a dark background to show contrast.
* background: '#1a1a1a'
* compact: false
* defaultShowCode: true
* transform: true
*/
import { Button } from 'my-component-lib';
export default () => ;
```
--------------------------------
### Define a Basic Global Component
Source: https://github.com/umijs/dumi/blob/master/docs/theme/global-component.md
Define a React functional component that accepts props and renders content. This example shows a simple component that displays a string prop.
```tsx
// Foo.tsx
import React, { type FC } from 'react';
const Foo: FC<{ barValue: string }> = (props) => (
当前 barValue 属性值为:{props.barValue}
);
export default Foo;
```
--------------------------------
### Render Multiple Demos in Columns
Source: https://github.com/umijs/dumi/blob/master/docs/guide/page-config.md
Multiple `` elements will be rendered in a two-column layout when 'demo.cols' is set to 2 in FrontMatter.
```html
分栏 1分栏 2分栏 3分栏 4
```
--------------------------------
### Patch Files and Update Metadata
Source: https://github.com/umijs/dumi/blob/master/suites/dumi-vue-meta/README.md
After updating files locally, use patchFiles to update the in-memory representation and trigger a recheck by the TypeChecker to get new type metadata.
```typescript
project.patchFiles([
{
action: 'add',
fileName: '...',
text: '...',
},
{
update: 'add',
fileName: '....',
text: '....',
},
]);
// Then you can get the new type metadata
const meta = project.service.getComponentLibraryMeta(entry);
```
--------------------------------
### 添加对 Kotlin 和 C# 语言的语法高亮支持
Source: https://github.com/umijs/dumi/blob/master/docs/guide/faq.md
通过在 .dumi/global.ts 文件中导入 prismjs 组件,可以为 dumi 添加对 Kotlin 和 C# 等语言的语法高亮支持。
```typescript
// .dumi/global.ts
import Prism from 'prism-react-renderer/prism';
(typeof global !== 'undefined' ? global : window).Prism = Prism;
require('prismjs/components/prism-kotlin');
require('prismjs/components/prism-csharp');
```
--------------------------------
### Configure Page TDK
Source: https://github.com/umijs/dumi/blob/master/docs/guide/page-config.md
Set page title, description, and keywords in FrontMatter to generate corresponding tags in the HTML head.
```markdown
---
title: 标题 # 配置页面标题,同时生成 标签
description: 描述 # 配置页面简介,同时用于生成 标签
keywords: [关键词] # 配置页面关键词,同时用于生成 标签
---
```
--------------------------------
### Get Site Configuration Data
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Access site configuration data using `useSiteData`. This includes package information, demo data, component data, locales, and theme configuration.
```typescript
import { useSiteData } from 'dumi';
const Example = () => {
const {
// 项目的 package.json 数据
pkg,
// 项目全量的 demo 数据
demos,
// 项目全量的组件数据(如果只需要单独获取这一份数据,请使用 useAtomAssets)
components,
// 项目的 locales 配置
locales,
// 用户从 .dumirc.ts 传入的 themeConfig
themeConfig,
// 当前页面的加载状态,由于默认启用路由按需加载,所以切换路由时会有 loading 的过程
loading,
} = useSiteData();
// 返回值:ISiteContext
// 类型定义:https://github.com/umijs/dumi/tree/master/src/client/theme-api/context.ts#L6
// 其他逻辑
};
```
--------------------------------
### Using the API Component in Markdown
Source: https://context7.com/umijs/dumi/llms.txt
Demonstrates how to use the `` component in a Markdown file to render the auto-generated API table for a component.
```APIDOC
## API
```
--------------------------------
### External Symbol Link Mapping Example
Source: https://github.com/umijs/dumi/blob/master/suites/dumi-vue-meta/README.md
Configure mappings for external symbol links, such as linking TypeScript's Promise to its MDN documentation. This allows for custom resolution of external types.
```js
{
typescript: {
Promise:
'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise',
},
}
```
--------------------------------
### openCodeSandbox
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Opens the current demo in CodeSandbox. Useful for custom demo previewer actions.
```APIDOC
## openCodeSandbox
### Description
Opens the current demo in CodeSandbox. This function is particularly useful when customizing the `PreviewerActions` component to provide an option to open the demo in CodeSandbox.
### Usage
```typescript
import { openCodeSandbox } from 'dumi';
// Example usage within a custom PreviewerActions component:
// openCodeSandbox(props);
```
### Parameters
This function accepts a single argument, `props`, which is typically the props passed to the `PreviewerActions` component, containing demo information.
```
--------------------------------
### Inline Component Demo
Source: https://context7.com/umijs/dumi/llms.txt
Renders a demo component directly within the documentation without a preview wrapper.
```APIDOC
## Inline Demo (no preview wrapper)
```jsx
/**
* inline: true
*/
import { Alert } from 'my-component-lib';
export default () => ;
```
```
--------------------------------
### External Demo File Reference
Source: https://context7.com/umijs/dumi/llms.txt
References an external React component file to be used as a demo, with options for title, description, and conditional rendering.
```APIDOC
## Advanced Filterable Table
```
--------------------------------
### Control Site Theme Color
Source: https://github.com/umijs/dumi/blob/master/docs/theme/api.md
Use `usePrefersColor` to get or set the site's theme color (dark or light). Useful for theme switching or controlling demo component themes.
```typescript
// .dumi/theme/layouts/GlobalLayout.tsx
import ConfigProvider from '@/config-provider';
import { useOutlet, usePrefersColor } from 'dumi';
const GlobalLayout: React.FC = ({ children }) => {
const outlet = useOutlet();
// color 为当前应用的主题色,dark or light
const [color] = usePrefersColor();
return {outlet};
};
```
```typescript
import { usePrefersColor } from 'dumi';
const Example = () => {
const [
// 当前生效的主题色,dark or light
color,
// 当前的偏好主题色,dark or light or auto
prefersColor,
// 设置偏好主题色,如果设置为 auto,则 color 的值会根据系统设置自动改变
setPrefersColor,
] = usePrefersColor();
// 可参考 dumi 默认主题的主题切换按钮实现:https://github.com/umijs/dumi/tree/master/src/client/theme-default/slots/ColorSwitch/index.tsx
// 其他逻辑
};
```
--------------------------------
### Include Demo Foo
Source: https://github.com/umijs/dumi/blob/master/src/loaders/markdown/transformer/fixtures/skip-only/case03/index.md
This code snippet is explicitly marked with 'only' and will be included.
```jsx
import React from 'react';
export default () => {
return (
Foo
);
};
```
--------------------------------
### createProjectByJson()
Source: https://github.com/umijs/dumi/blob/master/suites/dumi-vue-meta/README.md
Creates a component metadata checker using JSON configuration.
```APIDOC
## createProjectByJson()
### Description
Create component metadata checker through json configuration
### Type
```typescript
export declare function createProjectByJson(
options: CheckerProjectJsonOptions,
): Project;
```
### Parameters
- `options` [**_CheckerProjectJsonOptions_**](#) - An object containing JSON configuration options for the checker.
### Returns
- [`Project`](#) - The created Project instance.
```
--------------------------------
### Embedding External Markdown Files
Source: https://context7.com/umijs/dumi/llms.txt
Examples of using the '