主頁 > 企業開發 > Vue3 企業級優雅實戰 - 組件庫框架 - 9 實作組件庫 cli - 上

Vue3 企業級優雅實戰 - 組件庫框架 - 9 實作組件庫 cli - 上

2022-12-28 07:27:08 企業開發

上文搭建了組件庫 cli 的基礎架子,實作了創建組件時的用戶互動,但遺留了 cli/src/command/create-component.ts 中的 createNewComponent 函式,該函式要實作的功能就是勺ò釜篇提到的 —— 創建一個組件的完整步驟,本文咱們就依次實作那些步驟,(友情提示:本文內容較多,如果你能耐心看完、寫完,一定會有提升)

1 創建工具類

在實作 cli 的程序中會涉及到組件名稱命名方式的轉換、執行cmd命令等操作,所以在開始實作創建組件前,先準備一些工具類,

cli/src/util/ 目錄上一篇文章中已經創建了一個 log-utils.ts 檔案,現繼續創建下列四個檔案:cmd-utils.tsloading-utils.tsname-utils.tstemplate-utils.ts

1.1 name-utils.ts

該檔案提供一些名稱組件轉換的函式,如轉換為首字母大寫或小寫的駝峰命名、轉換為中劃線分隔的命名等:

/**
 * 將首字母轉為大寫
 */
export const convertFirstUpper = (str: string): string => {
  return `${str.substring(0, 1).toUpperCase()}${str.substring(1)}`
}
/**
 * 將首字母轉為小寫
 */
export const convertFirstLower = (str: string): string => {
  return `${str.substring(0, 1).toLowerCase()}${str.substring(1)}`
}
/**
 * 轉為中劃線命名
 */
export const convertToLine = (str: string): string => {
  return convertFirstLower(str).replace(/([A-Z])/g, '-$1').toLowerCase()
}
/**
 * 轉為駝峰命名(首字母大寫)
 */
export const convertToUpCamelName = (str: string): string => {
  let ret = ''
  const list = str.split('-')
  list.forEach(item => {
    ret += convertFirstUpper(item)
  })
  return convertFirstUpper(ret)
}
/**
 * 轉為駝峰命名(首字母小寫)
 */
export const convertToLowCamelName = (componentName: string): string => {
  return convertFirstLower(convertToUpCamelName(componentName))
}

1.2 loading-utils.ts

在命令列中創建組件時需要有 loading 效果,該檔案使用 ora 庫,提供顯示 loading 和關閉 loading 的函式:

import ora from 'ora'

let spinner: ora.Ora | null = null

export const showLoading = (msg: string) => {
  spinner = ora(msg).start()
}

export const closeLoading = () => {
  if (spinner != null) {
    spinner.stop()
  }
}

1.3 cmd-utils.ts

該檔案封裝 shelljs 庫的 execCmd 函式,用于執行 cmd 命令:

import shelljs from 'shelljs'
import { closeLoading } from './loading-utils'

export const execCmd = (cmd: string) => new Promise((resolve, reject) => {
  shelljs.exec(cmd, (err, stdout, stderr) => {
    if (err) {
      closeLoading()
      reject(new Error(stderr))
    }
    return resolve('')
  })
})

1.4 template-utils.ts

由于自動創建組件需要生成一些檔案,template-utils.ts 為這些檔案提供函式獲取模板,由于內容較多,這些函式在使用到的時候再討論,

2 引數物體類

執行 gen 命令時,會提示開發人員輸入組件名、中文名、型別,此外還有一些組件名的轉換,故可以將新組件的這些資訊封裝為一個物體類,后面在各種操作中,傳遞該物件即可,從而避免傳遞一大堆引數,

2.1 component-info.ts

src 目錄下創建 domain 目錄,并在該目錄中創建 component-info.ts ,該類封裝了組件的這些基礎資訊:

import * as path from 'path'
import { convertToLine, convertToLowCamelName, convertToUpCamelName } from '../util/name-utils'
import { Config } from '../config'

export class ComponentInfo {
  /** 中劃線分隔的名稱,如:nav-bar */
  lineName: string
  /** 中劃線分隔的名稱(帶組件前綴) 如:yyg-nav-bar */
  lineNameWithPrefix: string
  /** 首字母小寫的駝峰名 如:navBar */
  lowCamelName: string
  /** 首字母大寫的駝峰名 如:NavBar */
  upCamelName: string
  /** 組件中文名 如:左側導航 */
  zhName: string
  /** 組件型別 如:tsx */
  type: 'tsx' | 'vue'

  /** packages 目錄所在的路徑 */
  parentPath: string
  /** 組件所在的路徑 */
  fullPath: string

  /** 組件的前綴 如:yyg */
  prefix: string
  /** 組件全名 如:@yyg-demo-ui/xxx */
  nameWithLib: string

  constructor (componentName: string, description: string, componentType: string) {
    this.prefix = Config.COMPONENT_PREFIX
    this.lineName = convertToLine(componentName)
    this.lineNameWithPrefix = `${this.prefix}-${this.lineName}`
    this.upCamelName = convertToUpCamelName(this.lineName)
    this.lowCamelName = convertToLowCamelName(this.upCamelName)
    this.zhName = description
    this.type = componentType === 'vue' ? 'vue' : 'tsx'
    this.parentPath = path.resolve(__dirname, '../../../packages')
    this.fullPath = path.resolve(this.parentPath, this.lineName)
    this.nameWithLib = `@${Config.COMPONENT_LIB_NAME}/${this.lineName}`
  }
}

2.2 config.ts

上面的物體中參考了 config.ts 檔案,該檔案用于設定組件的前綴和組件庫的名稱,在 src 目錄下創建 config.ts

export const Config = {
  /** 組件名的前綴 */
  COMPONENT_PREFIX: 'yyg',
  /** 組件庫名稱 */
  COMPONENT_LIB_NAME: 'yyg-demo-ui'
}

3 創建新組件模塊

3.1 概述

上一篇開篇講了,cli 組件新組件要做四件事:

  1. 創建新組件模塊;
  2. 創建樣式 scss 檔案并匯入;
  3. 在組件庫入口模塊安裝新組件模塊為依賴,并引入新組件;
  4. 創建組件庫檔案和 demo,

本文剩下的部分分享第一點,其余三點下一篇文章分享,

src 下創建 service 目錄,上面四個內容拆分在不同的 service 檔案中,并統一由 cli/src/command/create-component.ts 呼叫,這樣層次結構清晰,也便于維護,

首先在 src/service 目錄下創建 init-component.ts 檔案,該檔案用于創建新組件模塊,在該檔案中要完成如下幾件事:

  1. 創建新組件的目錄;
  2. 使用 pnpm init 初始化 package.json 檔案;
  3. 修改 package.json 的 name 屬性;
  4. 安裝通用工具包 @yyg-demo-ui/utils 到依賴中;
  5. 創建 src 目錄;
  6. 在 src 目錄中創建組件本體檔案 xxx.tsx 或 xxx.vue;
  7. 在 src 目錄中創建 types.ts 檔案;
  8. 創建組件入口檔案 index.ts,

3.2 init-component.ts

上面的 8 件事需要在 src/service/init-component.ts 中實作,在該檔案中匯出函式 initComponent 給外部呼叫:

/**
 * 創建組件目錄及檔案
 */
export const initComponent = (componentInfo: ComponentInfo) => new Promise((resolve, reject) => {
  if (fs.existsSync(componentInfo.fullPath)) {
    return reject(new Error('組件已存在'))
  }

  // 1. 創建組件根目錄
  fs.mkdirSync(componentInfo.fullPath)

  // 2. 初始化 package.json
  execCmd(`cd ${componentInfo.fullPath} && pnpm init`).then(r => {
    // 3. 修改 package.json
    updatePackageJson(componentInfo)

    // 4. 安裝 utils 依賴
    execCmd(`cd ${componentInfo.fullPath} && pnpm install @${Config.COMPONENT_LIB_NAME}/utils`)

    // 5. 創建組件 src 目錄
    fs.mkdirSync(path.resolve(componentInfo.fullPath, 'src'))

    // 6. 創建 src/xxx.vue 或s src/xxx.tsx
    createSrcIndex(componentInfo)

    // 7. 創建 src/types.ts 檔案
    createSrcTypes(componentInfo)

    // 8. 創建 index.ts
    createIndex(componentInfo)

    g('component init success')

    return resolve(componentInfo)
  }).catch(e => {
    return reject(e)
  })
})

上面的方法邏輯比較清晰,相信大家能夠看懂,其中 3、6、7、8抽取為函式,

**修改 package.json ** :讀取 package.json 檔案,由于默認生成的 name 屬性為 xxx-xx 的形式,故只需將該欄位串替換為 @yyg-demo-ui/xxx-xx 的形式即可,最后將替換后的結果重新寫入到 package.json,代碼實作如下:

const updatePackageJson = (componentInfo: ComponentInfo) => {
  const { lineName, fullPath, nameWithLib } = componentInfo
  const packageJsonPath = `${fullPath}/package.json`
  if (fs.existsSync(packageJsonPath)) {
    let content = fs.readFileSync(packageJsonPath).toString()
    content = content.replace(lineName, nameWithLib)
    fs.writeFileSync(packageJsonPath, content)
  }
}

創建組件的本體 xxx.vue / xxx.tsx:根據組件型別(.tsx 或 .vue)讀取對應的模板,然后寫入到檔案中即可,代碼實作:

const createSrcIndex = (componentInfo: ComponentInfo) => {
  let content = ''
  if (componentInfo.type === 'vue') {
    content = sfcTemplate(componentInfo.lineNameWithPrefix, componentInfo.lowCamelName)
  } else {
    content = tsxTemplate(componentInfo.lineNameWithPrefix, componentInfo.lowCamelName)
  }
  const fileFullName = `${componentInfo.fullPath}/src/${componentInfo.lineName}.${componentInfo.type}`
  fs.writeFileSync(fileFullName, content)
}

這里引入了 src/util/template-utils.ts 中的兩個生成模板的函式:sfcTemplate 和 tsxTemplate,在后面會提供,

創建 src/types.ts 檔案:呼叫 template-utils.ts 中的函式 typesTemplate 得到模板,再寫入檔案,代碼實作:

const createSrcTypes = (componentInfo: ComponentInfo) => {
  const content = typesTemplate(componentInfo.lowCamelName, componentInfo.upCamelName)
  const fileFullName = `${componentInfo.fullPath}/src/types.ts`
  fs.writeFileSync(fileFullName, content)
}

創建 index.ts:同上,呼叫 template-utils.ts 中的函式 indexTemplate 得到模板再寫入檔案,代碼實作:

const createIndex = (componentInfo: ComponentInfo) => {
  fs.writeFileSync(`${componentInfo.fullPath}/index.ts`, indexTemplate(componentInfo))
}

init-component.ts 引入的內容如下:

import { ComponentInfo } from '../domain/component-info'
import fs from 'fs'
import * as path from 'path'
import { indexTemplate, sfcTemplate, tsxTemplate, typesTemplate } from '../util/template-utils'
import { g } from '../util/log-utils'
import { execCmd } from '../util/cmd-utils'
import { Config } from '../config'

3.3 template-utils.ts

init-component.ts 中引入了 template-utils.ts 的四個函式:indexTemplatesfcTemplatetsxTemplatetypesTemplate,實作如下:

import { ComponentInfo } from '../domain/component-info'

/**
 * .vue 檔案模板
 */
export const sfcTemplate = (lineNameWithPrefix: string, lowCamelName: string): string => {
  return `<template>
  <div>
    ${lineNameWithPrefix}
  </div>
</template>

<script lang="ts" setup name="${lineNameWithPrefix}">
import { defineProps } from 'vue'
import { ${lowCamelName}Props } from './types'

defineProps(${lowCamelName}Props)
</script>

<style scoped lang="scss">
.${lineNameWithPrefix} {
}
</style>
`
}

/**
 * .tsx 檔案模板
 */
export const tsxTemplate = (lineNameWithPrefix: string, lowCamelName: string): string => {
  return `import { defineComponent } from 'vue'
import { ${lowCamelName}Props } from './types'

const NAME = '${lineNameWithPrefix}'

export default defineComponent({
  name: NAME,
  props: ${lowCamelName}Props,
  setup (props, context) {
    console.log(props, context)
    return () => (
      <div class={NAME}>
        <div>
          ${lineNameWithPrefix}
        </div>
      </div>
    )
  }
})
`
}

/**
 * types.ts 檔案模板
 */
export const typesTemplate = (lowCamelName: string, upCamelName: string): string => {
  return `import { ExtractPropTypes } from 'vue'

export const ${lowCamelName}Props = {
} as const

export type ${upCamelName}Props = ExtractPropTypes<typeof ${lowCamelName}Props>
`
}

/**
 * 組件入口 index.ts 檔案模板
 */
export const indexTemplate = (componentInfo: ComponentInfo): string => {
  const { upCamelName, lineName, lineNameWithPrefix, type } = componentInfo

  return `import ${upCamelName} from './src/${type === 'tsx' ? lineName : lineName + '.' + type}'
import { App } from 'vue'
${type === 'vue' ? `\n${upCamelName}.name = '${lineNameWithPrefix}'\n` : ''}
${upCamelName}.install = (app: App): void => {
  // 注冊組件
  app.component(${upCamelName}.name, ${upCamelName})
}

export default ${upCamelName}
`
}

這樣便實作了新組件模塊的創建,下一篇文章將分享其余的三個步驟,并在 createNewComponent 函式中呼叫,

感謝你閱讀本文,如果本文給了你一點點幫助或者啟發,還請三連支持一下,點贊、關注、收藏,公\/同號 程式員優雅哥更多分享,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/540816.html

標籤:其他

上一篇:你是來找茬的吧?對自己的博客進行調優

下一篇:JS如何回傳異步呼叫的結果?

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • IEEE1588PTP在數字化變電站時鐘同步方面的應用

    IEEE1588ptp在數字化變電站時鐘同步方面的應用 京準電子科技官微——ahjzsz 一、電力系統時間同步基本概況 隨著對IEC 61850標準研究的不斷深入,國內外學者提出基于IEC61850通信標準體系建設數字化變電站的發展思路。數字化變電站與常規變電站的顯著區別在于程序層傳統的電流/電壓互 ......

    uj5u.com 2020-09-10 03:51:52 more
  • HTTP request smuggling CL.TE

    CL.TE 簡介 前端通過Content-Length處理請求,通過反向代理或者負載均衡將請求轉發到后端,后端Transfer-Encoding優先級較高,以TE處理請求造成安全問題。 檢測 發送如下資料包 POST / HTTP/1.1 Host: ac391f7e1e9af821806e890 ......

    uj5u.com 2020-09-10 03:52:11 more
  • 網路滲透資料大全單——漏洞庫篇

    網路滲透資料大全單——漏洞庫篇漏洞庫 NVD ——美國國家漏洞庫 →http://nvd.nist.gov/。 CERT ——美國國家應急回應中心 →https://www.us-cert.gov/ OSVDB ——開源漏洞庫 →http://osvdb.org Bugtraq ——賽門鐵克 →ht ......

    uj5u.com 2020-09-10 03:52:15 more
  • 京準講述NTP時鐘服務器應用及原理

    京準講述NTP時鐘服務器應用及原理京準講述NTP時鐘服務器應用及原理 安徽京準電子科技官微——ahjzsz 北斗授時原理 授時是指接識訓通過某種方式獲得本地時間與北斗標準時間的鐘差,然后調整本地時鐘使時差控制在一定的精度范圍內。 衛星導航系統通常由三部分組成:導航授時衛星、地面檢測校正維護系統和用戶 ......

    uj5u.com 2020-09-10 03:52:25 more
  • 利用北斗衛星系統設計NTP網路時間服務器

    利用北斗衛星系統設計NTP網路時間服務器 利用北斗衛星系統設計NTP網路時間服務器 安徽京準電子科技官微——ahjzsz 概述 NTP網路時間服務器是一款支持NTP和SNTP網路時間同步協議,高精度、大容量、高品質的高科技時鐘產品。 NTP網路時間服務器設備采用冗余架構設計,高精度時鐘直接來源于北斗 ......

    uj5u.com 2020-09-10 03:52:35 more
  • 詳細解讀電力系統各種對時方式

    詳細解讀電力系統各種對時方式 詳細解讀電力系統各種對時方式 安徽京準電子科技官微——ahjzsz,更多資料請添加VX 衛星同步時鐘是我京準公司開發研制的應用衛星授時時技術的標準時間顯示和發送的裝置,該裝置以M國全球定位系統(GLOBAL POSITIONING SYSTEM,縮寫為GPS)或者我國北 ......

    uj5u.com 2020-09-10 03:52:45 more
  • 如何保證外包團隊接入企業內網安全

    不管企業規模的大小,只要企業想省錢,那么企業的某些服務就一定會采用外包的形式,然而看似美好又經濟的策略,其實也有不好的一面。下面我通過安全的角度來聊聊使用外包團的安全隱患問題。 先看看什么服務會使用外包的,最常見的就是話務/客服這種需要大量重復性、無技術性的服務,或者是一些銷售外包、特殊的職能外包等 ......

    uj5u.com 2020-09-10 03:52:57 more
  • PHP漏洞之【整型數字型SQL注入】

    0x01 什么是SQL注入 SQL是一種注入攻擊,通過前端帶入后端資料庫進行惡意的SQL陳述句查詢。 0x02 SQL整型注入原理 SQL注入一般發生在動態網站URL地址里,當然也會發生在其它地發,如登錄框等等也會存在注入,只要是和資料庫打交道的地方都有可能存在。 如這里http://192.168. ......

    uj5u.com 2020-09-10 03:55:40 more
  • [GXYCTF2019]禁止套娃

    git泄露獲取原始碼 使用GET傳參,引數為exp 經過三層過濾執行 第一層過濾偽協議,第二層過濾帶引數的函式,第三層過濾一些函式 preg_replace('/[a-z,_]+\((?R)?\)/', NULL, $_GET['exp'] (?R)參考當前正則運算式,相當于匹配函式里的引數 因此傳遞 ......

    uj5u.com 2020-09-10 03:56:07 more
  • 等保2.0實施流程

    流程 結論 ......

    uj5u.com 2020-09-10 03:56:16 more
最新发布
  • 使用Django Rest framework搭建Blog

    在前面的Blog例子中我們使用的是GraphQL, 雖然GraphQL的使用處于上升趨勢,但是Rest API還是使用的更廣泛一些. 所以還是決定回到傳統的rest api framework上來, Django rest framework的官網上給了一個很好用的QuickStart, 我參考Qu ......

    uj5u.com 2023-04-20 08:17:54 more
  • 記錄-new Date() 我忍你很久了!

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 大家平時在開發的時候有沒被new Date()折磨過?就是它的諸多怪異的設定讓你每每用的時候,都可能不小心踩坑。造成程式意外出錯,卻一下子找不到問題出處,那叫一個煩透了…… 下面,我就列舉它的“四宗罪”及應用思考 可惡的四宗罪 1. Sa ......

    uj5u.com 2023-04-20 08:17:47 more
  • 使用Vue.js實作文字跑馬燈效果

    實作文字跑馬燈效果,首先用到 substring()截取 和 setInterval計時器 clearInterval()清除計時器 效果如下: 實作代碼如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta ......

    uj5u.com 2023-04-20 08:12:31 more
  • JavaScript 運算子

    JavaScript 運算子/運算子 在 JavaScript 中,有一些運算子可以使代碼更簡潔、易讀和高效。以下是一些常見的運算子: 1、可選鏈運算子(optional chaining operator) ?.是可選鏈運算子(optional chaining operator)。?. 可選鏈操 ......

    uj5u.com 2023-04-20 08:02:25 more
  • CSS—相對單位rem

    一、概述 rem是一個相對長度單位,它的單位長度取決于根標簽html的字體尺寸。rem即root em的意思,中文翻譯為根em。瀏覽器的文本尺寸一般默認為16px,即默認情況下: 1rem = 16px rem布局原理:根據CSS媒體查詢功能,更改根標簽的字體尺寸,實作rem單位隨螢屏尺寸的變化,如 ......

    uj5u.com 2023-04-20 08:02:21 more
  • 我的第一個NPM包:panghu-planebattle-esm(胖虎飛機大戰)使用說明

    好家伙,我的包終于開發完啦 歡迎使用胖虎的飛機大戰包!! 為你的主頁添加色彩 這是一個有趣的網頁小游戲包,使用canvas和js開發 使用ES6模塊化開發 效果圖如下: (覺得圖片太sb的可以自己改) 代碼已開源!! Git: https://gitee.com/tang-and-han-dynas ......

    uj5u.com 2023-04-20 08:01:50 more
  • 如何在 vue3 中使用 jsx/tsx?

    我們都知道,通常情況下我們使用 vue 大多都是用的 SFC(Signle File Component)單檔案組件模式,即一個組件就是一個檔案,但其實 Vue 也是支持使用 JSX 來撰寫組件的。這里不討論 SFC 和 JSX 的好壞,這個仁者見仁智者見智。本篇文章旨在帶領大家快速了解和使用 Vu ......

    uj5u.com 2023-04-20 08:01:37 more
  • 【Vue2.x原始碼系列06】計算屬性computed原理

    本章目標:計算屬性是如何實作的?計算屬性快取原理以及洋蔥模型的應用?在初始化Vue實體時,我們會給每個計算屬性都創建一個對應watcher,我們稱之為計算屬性watcher ......

    uj5u.com 2023-04-20 08:01:31 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:01:10 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:00:32 more