docz 用於把 md 文件自動構建成文檔網站,基於 mdx (markdowm + jsx),可以在 markdown 中引入 react 組件,並且支持熱更新,可以邊寫文檔邊調試。
官方效果圖長這樣:
下面就記錄一下怎樣把 docz 加入碗中。
安裝配置 docz
npm install docz -D
// doczrc.js
export default {
files: './components/**/*.{md,markdown,mdx}', // 匹配要處理的文件
dest: 'doc-site', // 打包出來的文件目錄名
title: 'xmh-ui', // 站點標題
typescript: true // ts 項目需開啟
}
使支持sass
npm install gatsby-plugin-sass -D
// gatsby-config.js
module.exports = {
plugins: ['gatsby-plugin-sass']
}
添加 script
"doc": "docz dev",
"build:doc": "rimraf doc-site && docz build", // rimraf 需另外安裝
"preview:doc": "docz serve"
使用
-
新建 mdx 文件
components/button/demo/index.mdx
-
編寫文檔
---
name: Button 按鈕
route: /Button
menu: 組件
---
import { Playground, Props } from 'docz';
import { Button } from '../index';
import '../Button.scss';
# Button 按鈕
## 參數
<Props of={Button} />
## 基本用法
<Playground>
<Button type="primary" size="large">
大號主按鈕
</Button>
</Playground>
-
執行
npm run doc
-
文檔顯示如下
問題
- 如上圖文檔顯示,
沒有支持 type 變量
// Button.tsx
export type sizeType = 'large' | 'middle' | 'small';
export type brandType = 'primary' | 'success' | 'error' | 'info' | 'warning';
export interface ButtonProps {
size?: sizeType;
type?: brandType;
loading?: boolean;
disabled?: boolean;
className?: string;
onClick?: React.MouseEventHandler<HTMLButtonElement>;
children?: React.ReactNode;
}
解決:
還是自己寫吧,更加靈活
-
沒有渲染出任何內容
解決:
去 github 查看了下 issue,發現很多人遇到了同樣的問題,issue地址。
應該是某些依賴導致的問題,使用 npm 會出現問題,yarn 則不會。
github 上有人給出了解決的 hack:
- Removed node_modules, package-lock.json
- Add "@mdx-js/mdx": "^1.6.16" explicitly as a dev dependency.
- npm install
- npm run docz dev
- Playgrounds work now.
照此操作,果然奏效了,現在文檔顯示如下:
- 如上圖,按鈕樣式沒有生效。
瀏覽器查看一下html
<div data-testid="live-preview" class="css-1yn7219-Playground">
<button id="button" class="$prefix-button $prefix-size-large $prefix-type-primary button">
大號主按鈕
</button>
</div>
如同預料,$prefix
沒有替換。這項操作本地啟動和打包時是在 webpack 中進行全局替換的,現在需要讓 docz 也能處理一下。
解決:
項目根目錄新建 gatsby-node.js,對 docz 所依賴的 gatby app 添加 webpack 配置。
// gatsby-node.js
const path = require('path');
exports.onCreateWebpackConfig = (args) => {
args.actions.setWebpackConfig({
module: {
rules: [
{
test: /\.(tsx|ts)$/,
/* ⚠ Note the '..' in the path because the docz gatsby project lives in the `.docz` directory */
include: [path.resolve(__dirname, '../components')],
exclude: [/node_modules/],
use: [
'ts-loader',
{
loader: 'webpack-replace-loader',
options: {
arr: [{ search: '$prefix', replace: 'xmh', attr: 'g' }]
}
}
]
}
]
}
});
};
注意:
- 配置里的 ../ 路徑,因為這個 gatsby 項目運行在 .docz 文件夾里。
- 這里為了直觀直接把
$prefix
替換成了ui名xmh
,實際上xmh
應該從一個 config.js 文件中引入。
好了,最后看一下現在的文檔: