如何在Vue项目中自动生成组件文档并展示到特定页面?

♫俊衡 阅读 72

我在用Vue 3开发管理后台时想集成组件库文档,尝试过用vue-docgen-api配合documentation库,按照官方文档配置了config.js


module.exports = {
  includes: 'src/components/**/*.{vue,js}',
  template: 'default',
  out: './docs'
}

但运行npx documentation build时提示Cannot find module 'vue-docgen-api/process',调整过依赖版本还是不行。想问下有没有更稳定的文档生成方案,或者怎么解决这个模块路径问题?另外生成后怎么把这些Markdown文档渲染到Vue路由里展示?

我来解答 赞 18 收藏
二维码
手机扫码查看
2 条解答
诗雯🍀
vue-docgen-api确实容易出问题,我建议直接用vuese来生成文档,更稳定也更现代。安装很简单:

npm install -D vuese


然后在项目根目录运行:

npx vuese gen --output docs/components


这样会把组件的props、slots、events等信息提取出来生成markdown。

至于渲染到页面,我写过一个简单的Markdown渲染组件,配合vue-router就能搞定:

const MarkdownRenderer = {
template:
,
data() {
return { rendered: '' }
},
mounted() {
import('showdown').then(showdown => {
fetch(this.$route.params.path)
.then(res => res.text())
.then(md => {
const converter = new showdown.Converter()
this.rendered = converter.makeHtml(md)
})
})
}
}


路由配置就简单了,类似这样:

{ path: '/docs/:path*', component: MarkdownRenderer }


这个方案清晰明了,维护起来也轻松。vuese的输出格式很规范,展示效果也不错。折腾半天vue-docgen-api不如换个思路,开发效率更高。
点赞
2026-03-30 18:07
UE丶炜曦
你这个问题确实有点坑,vue-docgen-api的兼容性有时候真的很让人头疼。我直接给你一个更稳定的方案:用vue-styleguidist,这玩意专门用来生成Vue组件文档,还自带预览功能,省心多了。

先装依赖:
npm install --save-dev vue-styleguidist


然后初始化配置:
npx vue-styleguidist init

这会生成一个.styleguide.config.js文件,里面可以配你要解析的组件路径,比如:
module.exports = {
components: 'src/components/**/[A-Z]*.vue',
};


启动看看效果:
npx vue-styleguidist server


至于怎么把生成的文档嵌到你的Vue项目里,可以用它的webpackConfig选项调整输出路径,或者直接在Vue路由里加个iframe指向它生成的HTML。代码放这了,你自己改改:
// router/index.js
{
path: '/docs',
name: 'Docs',
component: () => import('@/views/DocViewer.vue')
}


DocViewer.vue里写个简单的iframe:





这样就搞定了,比你自己折腾那些依赖版本问题强多了。反正我之前也踩过类似的坑,最后还是换工具比较省事。
点赞 8
2026-02-01 08:22