vue組件庫自動生成文檔-vue-styleguidist(一)


寫在前面:前面已經介紹了vue-press和vue-gocgen-cli和vue-press的區別和聯系,本篇文章主要介紹關於vue-styleguidist的使用

官網強大的api連接

生成組件可視化文檔原理

  • 編譯+生成可視化文檔
生成后的樣子

 

 生成文檔后的特點

  • .vue組件內容中可注釋的部分將生成組件文檔,類似於表格一樣的展示
  • 可運行組件的demo,並能夠點出示例

組件的目錄結構

核心配置文檔主要在於styleguide.config.js

 

啟動配置文件: 正常安裝 npm install vue-styleguidist

 "scripts": {
    "styleguide": "vue-styleguidist server",
    "styleguide:build": "vue-styleguidist build"
  },

styleguide.config.js 文檔參數配置說明

主要參數配置說明

1.組件參數配置說明

assetsDir 靜態資源配置文件目錄
components 可以是string類型,function 類型、或者Array 類型,通過配置components,找到可以生成的文檔文件
  components:'src/components/**/*.vue',
  components:[
   'src/components/**/index.vue',
   'src/components/**/index2.vue',
   'src/components/**/index3.vue',
  ],
  components:getComponentFiles(),
ignore 組件庫中配置忽略的文件 可string,可array ,function
  ignore =[
    '/iconfont/*.{vue,scss}',
    '/common/*.{vue,scss,js}',
    '/keyboard/*.{vue,scss,js}',
    '/dialog/*.{vue,scss,js}',
  ]
require 可用於運行編譯vue文件時候使用的第三方樣式
  require: [path.join(__dirname, 'styleguide/global.requires.js'),
            'babel-polyfill',
             path.join(__dirname, 'styleguide/styles.css')], //全局vue組件使用的插件

global.require.js 需要配置的vue組件運行時候需要的環境

/**
 * 全局插件組件庫
 * Styleguidist不加載main.js文件。為了安裝插件和組件庫,你需要在其他地方安裝插件和組件庫。
 * 首先創建一個安裝插件的.js文件。然后將其添加到styleguide.config.js文件中
 */

import Vue from 'vue' 

// 在組件庫的內部使用全局的utils.js文件需要在此引入
import "./../../assets/js/utils.js";
getComponentPathLine 生成組件文檔時候的引用提示語 根據自己文檔進行編寫
 getComponentPathLine(componentPath) {
      //獲取到當前組件的名字
    const componentFileName = path.basename(componentPath, '.vue')
    const name =
      componentFileName.toLowerCase() === 'index'
        ? path.basename(path.dirname(componentPath))//返回path的最后一部分
        : componentFileName
    return `import ${name} from '${componentPath.replace(/^src\//, '/')}'` //返回可復制的引用鏈接
  },

 

 

 

 version:string類型 當前版本信息 需要自己設置將顯示在組件中

webpackConfig : 組件編譯時候的配置,比如一些loader信息等
demo 配置一些vue進行運行編譯的文件
 rules = {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
    
      {
        test:/\.(css?|scss)(\?.*)?$/,
        use: ['style-loader', 'css-loader','sass-loader']
      }, 
      },

 在webpackConfig的設置的注意點

  • 在webpack設置上,原有的一些參數變量將會被直接忽略如: entry, externals, output, watch, stats option和生產環境以及開發環境配置
  • CommonsChunkPlugins, HtmlWebpackPlugin, UglifyJsPlugin, HotModuleReplacementPlugin插件將被忽略,因為Styleguidist已經包含了它們,否則它們可能會破壞Styleguidist。

以上是關於組件展示和運行的基礎信息配置

2.頁面參數配置
usageMode:文檔中屬性和方法的標簽初始化狀態,決定是否展開
  • collapse :默認情況下合上tab
  • hide:隱藏標簽,它不能在UI中被切換
  • expand:默認情況下展示選項卡

 

exampleMode:表示示例代碼是否展開或者合上文檔中代碼示例的標簽初始化狀態,決定是否展開
  • collapse:默認情況下折疊制表符。
  • hide:隱藏標簽,將不會展示在組件文檔中
  • expand:默認情況下展開選項卡。

copyCodeButton:代碼頂部的復制按鈕

 

 

 

locallyRegisterComponents:true/false
多個組件共享相同的名稱或,如果注冊了另一個組件,則組件將更改行為,在組件中存在兩個name為"rSelect"的組件,在創建的時候將只會創建一個,
theme:配置頁面的樣式,存在專門的配置文件
theme: {
    color: {
      link: 'firebrick',//鏈接顏色
      linkHover: 'salmon'//鏈接hover的顏色
    },
    fontFamily: {
      base: '"Comic Sans MS", "Comic Sans", cursive'
    }
  },

title:配置頁面標題&設置

 

sortProps:Function 對props的顯示排序,默認情況下是按照取的順序排序
module.exports = {
  sortProps: (props) => props
}
serverHost:'0.0.0.0', 啟動服務
serverPort:6060,端口
skipComponentsWithoutExample: 生成文檔時跳過沒有demo的組件,如我的button組件中沒有寫demo ,那么在生成文檔中將會跳過該組件
3.打包相關配置參數
 //打包配置
  compilerConfig: {
    target: { ie: 11 } 
  },
  progressBar:true,//打包進度條
   styleguidePublicPath:'./static',
  styleguideDir: 'dist', //打包文件放置的位置
  displayOrigins: false,  //是否顯示原位置的組件

組件文件路徑獲取

一個組件中存在多個.vue 文件,但是主要文件只有一個,因此需要自定義獲取主要文件配置,當主要組件名字不一致時候,我們無法去利用字符串components:src/components/**/*.vue進行生成文檔,因此需要進行文檔獲取配置。

在組件庫中,盡量保持暴露的主要文件名字規范才是最主要選擇,但是如果存在不一致的時候,需要我們進行手動修改組件的主要暴露名字或者去修改要生成的文件名字路徑,以本人組件庫為例子,在組件庫中,主要暴露文件有的是index.vue 有的是和文件名字一致的名字,因為需要在獲取時,進行主動獲取。
//獲取組件目錄文件配置
var getComponentFiles =function(path){
    var filesDir =[]; //存儲文件夾
    var files = fs.readdirSync(path); //獲取當前component的下的文件夾
    files.forEach((file)=>{
      
      var currBaseDir = path+'/'+file;//獲取當前文件目錄的地址
      var fileStat = fs.statSync(currBaseDir);  //獲取當前文件/目錄的屬性
      if(fileStat.isDirectory()){//如果是文件夾,則是我們需要遍歷的文件夾
        var fileChildren = fs.readdirSync(currBaseDir);//獲取當前文件目錄的子目錄結
        var regFile = new RegExp("^(index||"+file+")(.vue)") //正則匹配主要的文件 根據自己組件庫進行獲取主要暴露文件
        fileChildren.forEach((item,index)=>{ 
          var regResult = item.match(regFile)
          if(regResult && regResult.length >0){ 
            var chPath = currBaseDir+'/'+regResult[0];
            filesDir.push(chPath)//將獲取到的結果push到文件中
          }
        })
      }
    })
    return filesDir;
}  

得到的結果是:

[ './src/components/dialog/index.vue',
  './src/components/keyboard/index.vue',
  './src/components/loading/index.vue',
  './src/components/qrcode/index.vue',
  './src/components/rAction/index.vue',
  './src/components/rActionDemo/index.vue',
  './src/components/rAddress/rAddress.vue',]

保持組件命名規范是很重要的~

詳細配置文檔:

const path = require('path')

const { getComponentFiles, getIgnoreFiles } = require('./styleguide/config.js')

const themeObj = require('./styleguide/style/theme.js')//是組件的ui配置

var baseComponentsUrl = './components'

//獲取當前的環境 
const isProd = process.env.NODE_ENV === 'production'

//獲得當前組件的目錄結構
var componentFilesDir = getComponentFiles(baseComponentsUrl)
//獲取忽略生成組件目錄
var componentIgnoreDir = getIgnoreFiles(baseComponentsUrl)
module.exports = {
  title: '組件api && 運行',
  require: [path.join(__dirname, 'styleguide/global.requires.js')], //全局vue組件使用的插件
  components: componentFilesDir,
  ignore: componentIgnoreDir, //要忽略的生成組件的文件夾
  defaultExample: true,
  //使用組件引入路徑
  getComponentPathLine(componentPath) {
    const componentFileName = path.basename(componentPath, '.vue')
    const name =
      componentFileName.toLowerCase() === 'index'
        ? path.basename(path.dirname(componentPath))
        : componentFileName
    return `import ${name} from '${componentPath.replace(/^src\//, '/')}'`
  },
  // require: ['./docs/install.components.js'],  如何在樣式指南中隱藏一些組件,但在示例中使它們可用

  version: '1.1.1',
  webpackConfig: require('./webpack.js'),
  //頁面配置
  usageMode: 'expand', //文檔中屬性和方法的標簽初始化狀態,決定是否展開
  exampleMode: 'expand', //文檔中代碼示例的標簽初始化狀態,決定是否展開。
  copyCodeButton: true, //代碼頂部的復制按鈕
  locallyRegisterComponents: true, //vue-styleguidist全局注冊所有組件 多個組件共享相同的名稱或如果注冊了另一個組件,則組件將更改行為
  theme: themeObj,
   skipComponentsWithoutExample: true, //跳過沒有demo的vue組件案例
  pagePerSection: true, 

  //啟動服務配置
  serverHost: '0.0.0.0',
  serverPort: 6060,

  //打包配置
  compilerConfig: {
    target: { ie: 11 }
  },
  progressBar: true, //打包進度條
  // styleguidePublicPath: isProd? '/': '//static.ianguo.com/',
  styleguideDir: 'dist', //打包文件放置的位置
  displayOrigins: false
  //多個組件庫
  /**如果基本組件在一個包中,派生組件在另一個包中,那么您將希望文檔在公開的包中反映擴展組件的支持。*/
  // validExtends(fullFilePath) {
  //   return (
  //     /[\\/]@scoped[\\/]core[\\/]/.test(fullFilePath) ||
  //     !/[\\/]node_modules[\\/]/.test(fullFilePath)
  //   )
  // },
}

運行配置

運行配置其實就是為我們自己寫的demo配置一個運行環境

vue-styleguidist生成文檔即編譯過程,因為在編譯過程中組件需要的一些運行配置環境同樣也需要在vue-styleguidist進行配置,比如組件中使用了第三方插件,在vue-styleguidist也需要進行安裝,組件中使用的es6的語法,在vue-styleguidist運行中需要配置babel-loader,組件的樣式使用scss或者less進行編寫,也需要設置sass-loader或者less-loader;例如如下;

  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,  
        use: {
          loader: 'babel-loader',
          options: {
            sourceType: 'unambiguous',
            presets: [
              [
                '@babel/preset-env',
                {
                  // useBuiltIns: 'usage', 
                  targets: {
                    ie: '11'
                  }
                }
              ]
            ],
            comments: false
          }
        }
      },
      {
        test:/\.(css?|scss)(\?.*)?$/,
        use: ['style-loader', 'css-loader','sass-loader']
      },  
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        // loader: 'file-loader',
        options: {
          limit: 10000,
          name: '/fonts/[name].[ext]?v=[hash:8]',
        }
      },   
      {
        test:/\.svg$/,
        use:['svg-sprite-loader','svgo-loader'],  
      } 
    ]
  }, 
  plugins: [new vueLoader.VueLoaderPlugin()].concat(
    process.argv.includes('--analyze') ? [new BundleAnalyzerPlugin()] : []
  )

git的地址:https://github.com/YYNGUFD/vue-styleguide-demo

 

 

  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM