脚手架开发-流程介绍

450 阅读4分钟

「这是我参与2022首次更文挑战的第4天,活动详情查看:2022首次更文挑战

上次我们对脚手架实现原理做了介绍,这次介绍下开发流程,实现一个简单的脚手架

1. 开发流程

  • 创建npm项目
  • 创建脚手架入口文件,最上方添加:
#!/usr/bin/env node 
  • 配置package.json,添加bin属性
  • 编写脚手架代码
  • 将脚手架发布到npm

2. 使用流程

  • 安装脚手架 npm install -g your-own-cli
  • 使用脚手架 your-own-cli

3. 脚手架开发难点解析

  • 分包:将复杂的系统拆分成若干个模块
  • 命令注册:
vue create
vue add
vue invoke
  • 参数解析:
vue command [options] <params>
  • options全称:--version--help
  • options简写:-V-h
  • 带params的options:--path /Users/caimengxin/Desktop/vue-test
  • 帮助文档:
    • global help
      • Usage
      • Options
      • Commands
  • 示例:vue 的帮助信息:
Usage: vue <command> [options]

Options:
  -V, --version                              output the version number
  -h, --help                                 output usage information

Commands:
  create [options] <app-name>                create a new project powered by vue-cli-service
  add [options] <plugin> [pluginOptions]     install a plugin and invoke its generator in an already created project
  invoke [options] <plugin> [pluginOptions]  invoke the generator of a plugin in an already created project
  inspect [options] [paths...]               inspect the webpack config in a project with vue-cli-service
  serve [options] [entry]                    serve a .js or .vue file in development mode with zero config
  build [options] [entry]                    build a .js or .vue file in production mode with zero config
  ui [options]                               start and open the vue-cli ui
  init [options] <template> <app-name>       generate a project from a remote template (legacy API, requires @vue/cli-init)
  config [options] [value]                   inspect and modify the config
  outdated [options]                         (experimental) check for outdated vue cli service / plugins
  upgrade [options] [plugin-name]            (experimental) upgrade vue cli service / plugins
  migrate [options] [plugin-name]            (experimental) run migrator for an already-installed cli plugin
  info                                       print debugging information about your environment

  Run vue <command> --help for detailed usage of given command.
  • command help
    • Usage
    • Options

vue create 的帮助信息

Usage: create [options] <app-name>

create a new project powered by vue-cli-service

Options:
  -p, --preset <presetName>       Skip prompts and use saved or remote preset
  -d, --default                   Skip prompts and use default preset
  -i, --inlinePreset <json>       Skip prompts and use inline JSON string as preset
  -m, --packageManager <command>  Use specified npm client when installing dependencies
  -r, --registry <url>            Use specified npm registry when installing dependencies (only for npm)
  -g, --git [message]             Force git initialization with initial commit message
  -n, --no-git                    Skip git initialization
  -f, --force                     Overwrite target directory if it exists
  --merge                         Merge target directory if it exists
  -c, --clone                     Use git clone when fetching remote preset
  -x, --proxy <proxyUrl>          Use specified proxy when creating project
  -b, --bare                      Scaffold project without beginner instructions
  --skipGetStarted                Skip displaying "Get started" instructions
  -h, --help                      output usage information

还有很多,比如:

  • 命令行交互
  • 日志打印
  • 命令行文字变色
  • 网络通信:HTTP、WebSocket
  • 文件处理

等等......

4. 快速入门第一个脚手架

  1. 新建一个文件夹
mkdir test-cli
  1. 初始化项目
npm init -y
  1. 创建bin/index.js // 添加如下代码
#!/usr/bin/env node

console.log('cli test');
  1. 在package.js中添加如下命令
"bin": {
   "cli-test": "bin/index.js"
},
  1. 发布npm
  • 需要先登陆
npm login
npm publish
  1. 全局安装包
npm install -g ynzy-test-cli
  1. 执行命令
cli-test

  1. 通过which搜索cli-test
$ which cli-test
/c/Program Files/nodejs/cli-test

5.调试本地脚手架

安装本地脚手架

修改源码,使之和发布的脚手架代码版本不同

#!/usr/bin/env node

console.log('cli test!~!!');

目录下有脚手架(开发版)

在此目录下全局安装脚手架,会自动软连接到此目录下

执行脚本命令

移除全局包

npm remove -g test-cli

npm link

进入项目目录

使用npm link创建软连接

分包调试

在test-cli目录,平行创建一个新的目录 test-cli-lib

在test-cli-lib目录下创建lib目录,创建index文件编写源代码

在test-cli-lib目录下,终端执行npm link创建软连接

在test-cli目录下,终端执行npm link ynzy-test-cli-lib关联仓库

手动在package下加入此包

test-cli 引入此项目包

#!/usr/bin/env node
const lib = require('ynzy-test-cli-lib')
console.log(lib);
console.log('cli test!~!!');

执行cli-test报错

这是因为在ynzy-test-cli项目下,package中的main找不到index.js文件,修改main对应的文件路径

执行命令

移除link

npm unlink -g test-cli

6.脚手架本地link标准流程

链接本地脚手架:

cd your-cli-dir npm link

链接本地库文件

cd your-lib-dir npm link cd your-cli-dir npm link your-lib

取消链接本地库文件

cd your-lib-dir npm unlink cd your-cli-dir # link存在 npm unlink your-lib # link不存在 rm -rf node_modules npm install -S your-lib

理解npm link:

  • npm link your-lib:将当前项目中的node_modules下指定的库文件链接到node全局node_modules下的库文件
  • npm link:将当前项目链接到node全局node_modules中作为一个库文件,并解析bin配置创建可执行文件

理解npm unlink:

  • npm unlink:将当前项目从node全局node_modules中移除
  • npm unlink your-lib:将当前项目中的库文件依赖移除

7.脚手架命令注册和参数解析

注册一个命令 test-cli init

通过node默认库process下的argv属性可以获取到我们执行的参数

// test-cli/bin/index.js

#!/usr/bin/env node
console.log('test-cli');
const argv = require('process').argv;

执行

test-cli init

在lib中定义init方法供执行

// test-cli-lib/lib/index.js

module.exports = {
    sum(a, b) {
        return a + b;
    },
    init(){
        console.log('执行init流程');
    }
}

修改test-cli解析执行

// test-cli/bin/index.js
#!/usr/bin/env node

const lib = require('ynzy-test-cli-lib')
const argv = require('process').argv;

// 注册一个命令 test-cli init
const command = argv[2];

if (command) {
    if (lib[command]) {
        lib[command]()
    } else {
        console.log('无效的命令');
    }
} else {
    console.log('请输入命令');
}

实现参数解析 --version 和 init --name

参数解析 init --name

test-cli init --name vue-test

打印argv查看参数

$ test-cli init --name vue-test
test-cli
[
  'C:\Program Files\nodejs\node.exe',
  'C:\Program Files\nodejs\node_modules\ynzy-test-cli\bin\index.js',
  'init',
  '--name',
  'vue-test'
]
执行init流程

我们可以看到第4个参数是选项(option),第5个参数是选项的参数(param),解析这两个参数

// 实现参数解析 --version 和 init --name
const options = argv.slice(3)
let [option,param] = options
option = option.replace('--','')
console.log(option,param);

传入到命令方法中执行

#!/usr/bin/env node

const lib = require('ynzy-test-cli-lib')
// console.log(lib.sum(1,2));
console.log('test-cli');
const argv = require('process').argv;
// 注册一个命令 test-cli init
const command = argv[2];

// 实现参数解析 --version 和 init --name
const options = argv.slice(3)
let [option,param] = options
option = option.replace('--','')
console.log(option,param);

if (command) {
    if (lib[command]) {
        lib[command]({option,param})
    } else {
        console.log('无效的命令');
    }
} else {
    console.log('请输入命令');
}

修改lib下的init方法

module.exports = {
    sum(a, b) {
        return a + b;
    },
    init({option,param}){
        console.log('执行init流程',option,param);
    }
}

执行命令传入选项,命令对应的方法就可以获取到选项和参数了

参数解析 --version

// 实现参数解析 --version
if(command.startsWith('--') || command.startsWith('-')){
    // 全局的option
    const globalOption = command.replace(/--|-/g, '')
    console.log(globalOption);
    if(globalOption === 'version' || globalOption === 'V')
    console.log('1.0.0');
}

完整示例

// test-cli/bin/index.js

#!/usr/bin/env node

const lib = require('ynzy-test-cli-lib')
// console.log(lib.sum(1,2));
console.log('test-cli');
const argv = require('process').argv;
// 注册一个命令 test-cli init
const command = argv[2];

// 实现参数解析 init --name
const options = argv.slice(3)
if(options.length>1){
    let [option,param] = options
    option = option.replace('--','')
    console.log(option,param);

    if (command) {
        if (lib[command]) {
            lib[command]({option,param})
        } else {
            console.log('无效的命令');
        }
    } else {
        console.log('请输入命令');
    }
}
// 实现参数解析 --version
if(command.startsWith('--') || command.startsWith('-')){
    // 全局的option
    const globalOption = command.replace(/--|-/g, '')
    console.log(globalOption);
    if(globalOption === 'version' || globalOption === 'V')
    console.log('1.0.0');
}

// test-cli-lib/lib/index.js

module.exports = {
    sum(a, b) {
        return a + b;
    },
    init({option,param}){
        console.log('执行init流程',option,param);
    }
}

参数解析是比较复杂的,后面会使用第三方库

若有收获,就点个赞吧