logo头像

前端脚手架搭建

前端脚手架搭建

在实际开发过程中,从零开始建立项目的结构是一件让人头疼的事情,所以各种各样的脚手架工具运用而生。使用较多的yoeman,express-generato,create-react-appr和vue-cli便是当中之一。它们功能丰富,但最核心的功能都是能够快速搭建一个完整的项目结构,开发者只需要在生成的项目结构基础上进行开发即可,非常简单高效。

  1. 为什么需要需要脚手架?
  • 减少重复性的工作,不再需要复制其他项目再删除无关代码,或者从零创建一个项目和文件
  • 根据交互动态生成项目结构和配置文件等。

我们可以借鉴 vue-cli 的基本思路。vue-cli 是将项目模板放在 git 上,运行的时候再根据用户交互下载不同的模板,经过模板引擎渲染出来,生成项目。这样将模板和脚手架分离,就可以各自维护,即使模板有变动,只需要上传最新的模板即可,而不需要用户去更新脚手架就可以生成最新的项目。那么就可以按照这个思路来进行开发了。

  1. 第三方库
  • commander.js,可以自动的解析命令和参数,用于处理用户输入的命令。
  • download-git-repo,下载并提取 git 仓库,用于下载项目模板。
  • Inquirer.js,通用的命令行用户界面集合,用于和用户进行交互。
  • handlebars.js,模板引擎,将用户提交的信息动态填充到文件中。
  • ora,下载过程久的话,可以用于显示下载中的动画效果。
  • chalk,可以给终端的字体加上颜色。
  • log-symbols,可以在终端上显示出 √ 或 × 等的图标。
  1. 初始化项目
    首先创建一个空项目,暂时命名为 all-cli,然后新建一个 cli.js 文件,再执行 npm init 生成一个 package.json 文件。最后安装上面需要用到的依赖。
1
2
3
4
5
mkdir all-cli && cd all-cli

npm init

npm install commander download-git-repo inquirer handlebars ora chalk log-symbols -S
  1. 处理命令行
    node.js 内置了对命令行操作的支持,在 package.json 中的 bin 字段可以定义命令名和关联的执行文件。
    所以现在 package.json 中加上 bin 的内容:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    {
    "name": "all-cli",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "bin": {
    "all-cli": "bin/cli.js"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
    "chalk": "^2.4.2",
    "commander": "^2.20.0",
    "download-git-repo": "^1.1.0",
    "handlebars": "^4.1.2",
    "inquirer": "^6.3.1",
    "log-symbols": "^3.0.0",
    "ora": "^3.4.0"
    }
    }

然后在cli.js中定义init命令:

1
2
3
4
5
6
7
8
#!/usr/bin/env node
const program = require('commander');
program.version('1.0.0', '-v, --version')
.command('init <name>')
.action((name) => {
console.log(name);
});
program.parse(process.argv);

调用 version(‘1.0.0’, ‘-v, –version’) 会将 -v 和 –version 添加到命令中,可以通过这些选项打印出版本号。
调用 command(‘init ‘) 定义 init 命令,name 则是必传的参数,为项目名。
action() 则是执行 init 命令会发生的行为,要生成项目的过程就是在这里面执行的,这里暂时只打印出 name。
这里已经可以执行 init 命令了。执行:

1
node bin/cli.js init HelloWorld

可以看到命令行工具也打印出了 HelloWorld,那么很清楚, action((name) => {}) 这里的参数 name,就是我们执行 init 命令时输入的项目名称。
命令已经完成,接下来就要下载模板生成项目结构了。

  1. 下载模板
    download-git-repo 支持从 Github、Gitlab 和 Bitbucket 下载仓库,各自的具体用法可以参考官方文档。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    #!/usr/bin/env node
    const program = require('commander');
    const download = require('download-git-repo');
    program.version('1.0.0', '-v, --version')
    .command('init <name>')
    .action((name) => {
    download('gitlab:xx#master', name, {clone: true}, (err) => {
    console.log(err ? 'Error' : 'Success')
    })
    });
    program.parse(process.argv);
  2. 命令行交互
    命令行交互功能可以在用户执行 init 命令后,向用户提出问题,接收用户的输入并作出相应的处理。这里使用 inquirer.js 来实现。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const inquirer = require('inquirer');
    inquirer.prompt([
    {
    type: 'input',
    name: 'author',
    message: 'author'
    }
    ]).then((answers) => {
    console.log(answers.author);
    })

通过这里例子可以看出,问题就放在 prompt() 中,问题的类型为 input 就是输入类型,name 就是作为答案对象中的 key,message 就是问题了,用户输入的答案就在 answers 中,使用起来就是这么简单。更多的参数设置可以参考官方文档。
通过命令行交互,获得用户的输入,从而可以把答案渲染到模板中。

  1. 渲染模板
    这里用 handlebars 的语法对仓库的模板中的 package.json 文件做一些修改
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    {
    "name": "{{name}}",
    "author": "{{author}}",
    "version": "{{version}}",
    "description": "{{description}}",
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "license": "ISC"
    }

并在下载模板完成之后将用户输入的答案渲染到 package.json 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
program.version('1.0.0', '-v, --version')
.command('init <name>')
.action((name) => {
inquirer.prompt([
{
name: 'description',
message: 'description'
},
{
name: 'author',
message: 'author'
}
]).then((answers) => {
download('gitlab:xxxx#master',name,{clone: true},(err) => {
const meta = {
name,
description: answers.description,
author: answers.author
}
const fileName = `${name}/package.json`;
const content = fs.readFileSync(fileName).toString();
const result = handlebars.compile(content)(meta);
fs.writeFileSync(fileName, result);
})
})
});

这里使用了 node.js 的文件模块 fs,将 handlebars 渲染完后的模板重新写入到文件中。

  1. 视觉美化
    在用户输入答案之后,开始下载模板,这时候使用 ora 来提示用户正在下载中。
    1
    2
    3
    4
    5
    6
    7
    8
    const ora = require('ora');
    // 开始下载
    const spinner = ora('The template is being downloaded...');
    spinner.start();
    // 下载失败调用
    spinner.fail();
    // 下载成功调用
    spinner.succeed();

然后通过 chalk 来为打印信息加上样式,比如成功信息为绿色,失败信息为红色,这样子会让用户更加容易分辨,同时也让终端的显示更加的好看。

1
2
3
const chalk = require('chalk');
console.log(chalk.green('Success'));
console.log(chalk.red('Fail'));

除了给打印信息加上颜色之外,还可以使用 log-symbols 在信息前面加上 √ 或 × 等的图标。

1
2
3
4
const chalk = require('chalk');
const symbols = require('log-symbols');
console.log(symbols.success, chalk.green('Success'));
console.log(symbols.error, chalk.red('Fail'));

  1. 完整示例
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    #! /usr/bin/env node
    const program = require('commander');
    const download = require('download-git-repo');
    const inquirer = require('inquirer');
    const handlebars = require('handlebars');
    const ora = require('ora');
    const chalk = require('chalk');
    const symbols = require('log-symbols');
    const fs = require("fs");
    program.version('1.0.0', '-v', '--version')
    .command('init <name>')
    .action((name) => {
    if (!fs.existsSync(name)) {
    inquirer.prompt([
    {
    type: 'list',
    choices: ['umi', 'react-webpack', 'react-antd'],
    name: 'platform',
    message: 'Please select the project you want to install.'
    }, {
    name: 'version',
    message: 'version:(1.0.0)'
    }, {
    name: 'description',
    message: 'description:'
    }, {
    name: 'author',
    message: 'author:'
    }]).then((answers) => {
    console.log(answers.author);
    const spinner = ora('The template is being downloaded...');
    const platform = answers.platform;
    spinner.start();

    download('https://github.com/879733672/all-web-cli.git#{platform}', name, { clone: true }, (err) => {
    if (err) {
    spinner.fail();
    console.log(symbols.error, chalk.red(err));
    } else {
    spinner.succeed();
    const fileName = `{name}/package.json`;
    const meta = {
    name,
    description: answers.description,
    author: answers.author,
    version: answers.version || '1.0.0'
    }
    if (fs.existsSync(fileName)) {
    const content = fs.readdirSync(fileName).toString();
    const result = handlebars.compile(content)(meta);
    fs.writeFileSync(fileName, result);
    }
    console.log(symbols.success, chalk.green('Done'))
    }
    });
    });
    }else {
    //错误提示项目已存在,避免覆盖原有项目
    console.log(symbols.error, chalk.red("Already Existed."));
    }
    });

    program.parse(process.argv);

完成之后,就可以把脚手架发布到 npm 上面,通过 -g 进行全局安装,就可以在自己本机上执行 ice init [name] 来初始化项目,这样便完成了一个简单的脚手架工具了