Vuepress2+tsx组件

1,217 阅读2分钟

👀前言

经过很多很多很多次的迭代后🙈,我司项目里组件有点多,一堆组件零零散散的,也没有文档,所以新同事刚接触项目的时候会很懵,需要耗费较多的时间在熟悉组件上。
上周五我的组长让我开始慢慢把项目的组件库文档搭起来。我司的技术栈是vue3+tsx+webpack,既然用vue的组件库文档,那肯定是vuepress啊,省时又好用。

❗️❗️这里提醒一下:vue3是必须用vuepress2的

🛠️配置

基础搭建

直接按照 vuepress2文档 提供的步骤去做就可以了。

webpack配置

因为我们公司项目的技术栈用到了webpack,所以我没有用vite而是用了webpack去配置vuepress。

主要配置

因为我司项目是用了tsx语法,所以需要用babel-loader通过jsx语法编译,vue3文档中有提到一个babel插件。

这就是为什么会有一个 Babel 插件,用于在 Vue 中使用 JSX 语法,它可以让我们回到更接近于模板的语法上。

开始上手

package.json

把依赖先安装好

"devDependencies": {
    "@babel/core": "^7.16.5",
    "@babel/preset-env": "^7.16.5",
    "@vue/babel-plugin-jsx": "^1.1.1",
    "@vuepress/bundler-webpack": "^2.0.0-beta.30",
    "babel-loader": "^8.2.3",
    "ts-loader": "8.0.0",
    "typescript": "^4.5.4",
    "vuepress": "^2.0.0-beta.31"
  }

docs > .vuepress > config.ts

这里只展示配置webpack的部分。

import { defineUserConfig } from 'vuepress'
import type { DefaultThemeOptions } from 'vuepress'
export default defineUserConfig<DefaultThemeOptions>({
  bundler: '@vuepress/bundler-webpack',//将打包工具设置为webpack
  // Webpack 打包工具的配置项
  bundlerConfig: {
    configureWebpack: () => {
      return {
        module: {
          rules: [{
            test: /\.tsx$/,
            exclude: /node_modules/,
            use: [
              {
                loader: 'babel-loader',
                options: {
                  babelrc: false,
                  configFile: false,
                  presets: [
                    '@babel/preset-env',
                  ],
                  plugins: ["@vue/babel-plugin-jsx"]
                }
              },
              'ts-loader'
            ]
          }]
        }
      }
    }
  },

})

🗡️牛刀小试

这里需要配一个guide/getting-started.md的侧边栏,侧边栏根据vuepress2官方文档去配,很简单,这里就不多赘述了。

目录结构:

|-- docs
| |-- .vuepress
| |-- clientAppEnhance.ts
| | |-- components
| | | |-- Button.tsx
| |-- guide
| | |-- getting-started.md

docs > .vuepress > clientAppEnhance.ts

import { defineClientAppEnhance } from '@vuepress/client'
import Button from './components/Button'
export default defineClientAppEnhance(({ app, router, siteData }) => {
  app.component('myButton', Button)
})

docs > .vuepress > components >Button.tsx

import { defineComponent } from 'vue'
export default defineComponent({
  setup() {
    return () => (<div>button</div>)
  }
})

docs > guide > getting-started.md

<myButton />

页面显示:

微信截图_20211229210600.png

📚参考资料

github|vuejs/jsx-next

VuePress2官网

🌟结语

由于本人经验水平有限,难免会有纰漏,对此欢迎指正。 😄