1. 首页
  2. 技术知识

Vue3 企业级优雅实战 – 组件库框架 – 8 搭建组件库 cli

前面的文章分享了组件库的开发、example、组件库文档,本文分享组件库 cli 开发。


1 为什么要开发组件库 cli

回顾一个新组件的完整开发步骤:


1 在 packages 目录下创建组件目录 xxx: 1.1 使用 pnpm 初始化 package.json,修改 name 属性; 1.2 在该目录中创建 src 目录和 index.ts 文件; 1.3 在 src 目录下创建 types.ts 文件和 index.tsx / index.vue 文件;


2 在组件库的入口模块 packages/yyg-demo-ui: 2.1 使用 pnpm install 安装 1.1 创建的 xxx; 2.2 在 packages/xxx-ui/index.ts 中引入 xxx,并添加到 components 数组中;


3 packages/scss/components/ 目录: 3.1 在该目录下创建 _xxx.module.scss; 3.2 在该目录中的 index.scss 中引入 _xxx.module.scss;


4 组件库文档: 4.1 在 docs/components 目录下创建 xxx.md 文件; 4.2 在 docs/demos 目录下创建 xxx 目录,并在该目录中创建 xxx.vue 文件; 4.3 在 docs/components.ts 中添加组件菜单项;


该步骤是一个机械化的流程操作,涉及新建或修改十多个文件,费事费力,纯属体力活。这种情况下就可以使用工具替代咱们完成这些操作,开发一个 cli,执行命令、输入组件名就自动创建组件,完成上述操作,如此便可以将注意力集中到组件和业务的开发中。


2 开发 cli 使用到的技术

开发 cli 的库有很多,优雅哥在这里使用的还是最传统的技术栈,在下面使用的这些库时要注意版本号:

版本 作用
commander ^9.4.1 接收输入的命令,解析命令参数
chalk 4.1.2 控制台输出的文字颜色
inquirer 8.2.5 命令行交互,在命令行提示用户输入,获取到用户输入的内容
log-symbols 4.1.0 控制台输出的图标,如 success、failure 等状态
ora 5.4.1 在控制台显示 loading
shelljs ^0.8.5 执行 cmd 命令,如 cd、pnpm install 等


3 搭建 cli 开发框架

有了上面的知识准备,接下来就进入实战 cli:


3.1 初始化 cli 模块

在命令行中进入 cli 目录,依旧使用 pnpm 初始化:

pnpm init
修改生成的
package.json
文件
name
属性:

{  “name”: “@yyg-demo-ui/cli”,  “version”: “1.0.0”,  “description”: “命令行工具”,  “author”: “程序员优雅哥”,  “license”: “ISC”}

cli
目录下创建 ts 配置文件
tsconfig.json


{  “compilerOptions”: {    “target”: “es2015”,    “lib”: [      “es2015”    ],    “module”: “commonjs”,    “rootDir”: “./”,    “allowJs”: true,    “isolatedModules”: false,    “esModuleInterop”: true,    “forceConsistentCasingInFileNames”: true,    “strict”: true,    “skipLibCheck”: true  }}

cli
目录下创建
index.ts
文件作为入口:

#!/usr/bin/env nodeconsole.log(‘hello cli!’)

该文件第一行不能省略,这句话的意思是使用 node 来执行这个文件,并且在 /use/bin/env 环境变量中去找 node 执行器。

3.2 ts-node 执行 ts 文件

有了入口文件,怎么去执行它呢?当前 index.ts 中没有任何 TypeScript 语法,可以使用
node index.js
来执行,但有 TypeScript 语法时,就需要 tsc 先编译 ts 文件,再使用 node 命令来执行。这样每次运行比较麻烦,庆幸可以使用
ts-node
来执行。



cli
目录下按照
ts-node
为开发依赖:

pnpm install ts-node -D
可以尝试在命令行中执行
ts-node index.ts



直接这么执行不优雅,优雅哥更宁愿在
cli

package.json
添加
scripts


“scripts”: {  “gen”: “ts-node ./index.ts create”},
在上面的
gen
命令中,添加了一个参数
create
,在后面会解析出这个参数。


重新在命令行执行:

pnpm run gen
控制台能正常输出
hello cli!
,ts 文件可以正常执行。


3.3 源码目录

上面创建的 index.ts 是命令执行的入口,现在咱们在
cli
中创建
src
目录存放源码,并在
src
中创建 index.ts 作为源码的入口,首先在该文件中定义一个入口函数:


src/index.ts


export const mainEntry = () => {  console.log(‘hello cli mainEntry’)}
在外层的
index.ts
中(
cli/index.ts
)调用该函数:

#!/usr/bin/env nodeimport { mainEntry } from ‘./src’mainEntry()
执行
pnpm run gen
测试程序是否正常运行。


3.4 参数解析

前面定义的
gen
命令携带了参数
create
,要怎么解析出这个参数呢?可以使用
commander
库来完成。



cli
中安装
commander


pnpm install commander -D
修改
cli/src/index.ts
文件,使用
commander
来解析参数:

import { program } from ‘commander’export const mainEntry = () => {  console.log(‘hello cli mainEntry’)  program.version(require(‘../package’).version)    .usage(‘<command> [arguments]’)  program.command(‘create’)    .description(‘create a new component’)    .alias(‘c’)    .action(() => {      console.log(‘创建组件’)    })  program.parse(process.argv)  if (!program.args.length) {    program.help()  }}
如果直接执行
ts-node index.ts
,会输出命令使用帮助:

hello cli mainEntryUsage: index <command> [arguments]Options:  -V, –version   output the version number  -h, –help      display help for commandCommands:  create|c        create a new component  help [command]  display help for command
执行
pnpm run gen
(即
ts-node index.ts create
),则会进入 create 命令的 action 回调函数中:

hello cli mainEntry创建组件

cli/src/
目录下创建目录
command
,并在该目录中创建
create-component.ts
文件,该文件用于处理参数为
create
时执行的内容(即创建组件相关的目录文件等):

export const createComponent = () => {  console.log(‘创建新组建’)}
该文件导出了函数
createComponent
,该函数的内部实现逻辑咱们在下一篇文章实现,本文先将 cli 架子搭起来。


修改
cli/src/index.ts
文件,首先引入 createComponent 函数,然后在
create
命令的
action
中调用它:

…import { createComponent } from ‘./command/create-component’export const mainEntry = () => {  …  program.command(‘create’)    …    action(createComponent)        …}
执行
gen
命令时,就会调用到
createComponent
函数了。


3.5 用户交互


createComponent
中,首先要提示组件开发人员输入组件的名称、中文名、组件类型(tsx、vue),这时候可以使用
inquirer
来实现。先在
cli
下安装依赖,为了省事,咱把其他依赖一起安装了:

pnpm install chalk@4.1.2 inquirer@8.2.5 @types/inquirer@8.2.5 log-symbols@4.1.0 ora@5.4.1 shelljs  @types/shelljs -D
接着在
create-component.ts
中定义交互提示和变量名:

import inquirer, { QuestionCollection } from ‘inquirer’// 交互提示const questions: QuestionCollection = [  {    name: ‘componentName’,    message: ‘Input the component name: ‘,    default: ”  },  {    name: ‘description’,    message: ‘Input the component description: ‘,    default: ”  },  {    type: ‘list’,    name: ‘componentType’,    message: ‘Choose the component type: ‘,    choices: [      ‘tsx’, ‘vue’    ]  }]
最后在
createComponent
函数中使用
inquirer
实现交互提示信息:

const createNewComponent = (componentName: string, description: string, componentType: string) => {  console.log(componentName, description, componentType)}export const createComponent = () => {  inquirer.prompt(questions).then(({ componentName, description, componentType }) => {    createNewComponent(componentName, description, componentType)  })}
执行
pnpm run gen
运行效果如下:


到这里,组件库 cli 的架子咱们就搭建起来了,后面只需要实现
createNewComponent
函数即可,在该函数中创建目录、文件、执行命令等。


3.6 美化日志

本文最后咱们玩点
优雅
的东西。如果直接使用
console.log
输出,只有黑白色,不优雅,咱可以使用
chalk
改变输出的文字的颜色,并通过
log-symbols
加些图标。首先在
src
下创建
util
目录,在该目录中创建
log-utils.ts
文件,用来封装优雅版的
console.log


import chalk from ‘chalk’import logSymbols from ‘log-symbols’export const r = (msg: string, showIcon = true): void => {  if (showIcon) {    console.log(logSymbols.error, chalk.red(msg))  } else {    console.log(chalk.red(msg))  }}export const g = (msg: string, showIcon = true): void => {  if (showIcon) {    console.log(logSymbols.success, chalk.green(msg))  } else {    console.log(chalk.green(msg))  }}export const c = (msg: string): void => {  console.log(logSymbols.info, chalk.cyan(msg))}
该文件导出了 r、g、c 三个函数,其他文件使用时非常简便:

c(‘yyg-demo-ui cli 工具’)
本文搭建好 cli 的架子,下文将完成
createNewComponent
函数,实现组件创建的全过程。

原创文章,作者:starterknow,如若转载,请注明出处:https://www.starterknow.com/126682.html

联系我们