脚手架开发教程

321 阅读2分钟

什么是脚手架

脚手架是为了保证各施工过程顺利进行而搭设的工作平台。

脚手架的意义

  • 能够快速生成新项目。
  • 能够提升开发效率。

web-cli 实现的功能

webCli init <project-name> // 初始化项目
webCli create <name> // 创建页面/组件模版

创建cli工程

mkdir web-cli
cd web-cli
npm init -y
mkdir bin //新建bin目录
touch index.js

bin目录中的index.js文件 用来指定脚本的环境

#! /usr/bin/env node // 指定环境为node环境

require('../index.js') // 将逻辑写在外面的js中

修改package.json文件

新增bin字段 里面的script脚本用来启动执行该脚手架 即 'oss'

{
    "name": "web-cli",
    "version": "1.0.0",
    "description": "web cli",
    "main": "index.js",
    "bin": {
        "webCli": "./bin/index.js"
    },
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "repository": {
        "type": "git"
    },
    "keywords": [
        "oss",
        "cli"
    ],
    "engines": {
        "node": ">=7.6"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "chalk": "^4.1.0",
        "commander": "^6.2.0",
        "cross-spawn": "^7.0.3",
        "del": "^6.0.0",
        "download-git-repo": "^3.0.2",
        "figlet": "^1.5.0",
        "inquirer": "^7.3.3",
        "ora": "^5.1.0",
        "semver": "^7.3.2",
        "valid-filename": "^3.1.0",
    }
}

项目结构

web-cli
├─bin
|  └index.js
├─index.js
├─template
├─libs
|  ├─create.js
|  ├─init.js
|  ├─utils
|  |   ├─cleanArgs.js
|  |   ├─fsHelper.js
|  |   ├─common
|  |   |   ├─exit.js
|  |   |   ├─index.js
|  |   |   ├─log.js
|  |   |   └spinner.js
├─package.json
├─README.md

常用插件

npm install commander inquirer chalk download-git-repo json-format --save
  1. commander 可以帮助我们快速的读取处理命令行命令
  2. inquirer 可以自定义输入项 来做一些定制化需求
  3. chalk figlet 用来美化控制台输出
  4. ora 用来显示进度条
  5. download-git-repo 用来下载已编辑好的模版
  6. cross-spawn 开启子进程来执行脚本
  7. semver 版本比对

创建项目

执行下面的命令

webCli init <oss-test-project>
program
    .command('init <projectName>')
    .alias('i')
    .description('init web project')
    .action(async (projectName, cmd) => {
        if (process.argv.slice(3).length > 1) {
            log.warn('>>> 检测到您输入多个文件名, 我们将默认选取第一个作为项目名称');
        }
        const options = cleanArgs(cmd);
        await require('./libs/init')(projectName, options);
    });

新建页面/组件模版

program
    .command('create <name>')
    .description('create a new page or component')
    .option('-p, --page', 'Create a new page')
    .option('-c, --component', 'Create a new component')
    .action((name, cmd) => {
        const options = cleanArgs(cmd);
        require('./libs/create')(name, options);
    });

调试

Node规定,使用一个模块时,需要将其安装到全局的或项目的node_modules目录之中。对于开发中的模块,解决方法就是在全局的node_modules目录之中,生成一个符号链接,指向模块的本地目录。 npm link就能起到这个作用,会自动建立这个符号链接。

npm link

执行完命令后就可以在控制台进行开发调试了

注意

  1. process.cwd()和__dirname的区别 process.cwd()返回当前工作目录。如:调用node命令执行脚本时的目录。 __dirname返回源代码所在的目录。