使用 yeoman 自动化搭建前端脚手架

1,266 阅读2分钟
原文链接: www.jianshu.com

yeoman

一个比较出名和使用了一段时间的搭建脚手架工具,从grunt 开始 到webpack 都可以用它。

目前很多框架都会有自己的client , 阿里和饿了么等大公司也有自己的搭建工具。

不过yeoman依然是一个简单高效的选择。

开始

# 全局安装工具
npm install -g yo

# 就一个yo 就可以构架项目了, generator 可以在里面搜索和下载
yo

generator 就是脚手架的搭建器,可以搭建不同的脚手架

开发自己的generator

使用generator-generator 来generator你的generator

    npm i generator-generator -g

    yo

    npm i

目录结构:

    generator
        |-- app
             |--templates   // 你的脚手架模板
             |-- index.js  // 核心coding部分

    gulpfile.js
    README.md
    package.json

yo的运行周期

每一个方法中的 this 都被绑定为 Generator 实例本身

   1. initializing - 初始化一些状态之类的,通常是和用户输入的 options 或者 arguments 打交道,这个后面说。

   2. prompting - 和用户交互的时候(命令行问答之类的)调用。

   3. configuring - 保存配置文件(如 .babelrc 等)。

   4. default - 其他方法都会在这里按顺序统一调用。

   5. writing - 在这里写一些模板文件。

   6. conflicts - 处理文件冲突,比如当前目录下已经有了同名文件。

   7. install - 开始安装依赖。

   8. end - 擦屁股的部分... Say Goodbye maybe...

yo 的常用API

启动

yosay 是一个yo的特定的log组件,会带上yo的图标

var yosay = require('yosay');
// Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the peachy ' + chalk.red('generator-fallen-angel') + ' generator!'
    ));

用户交互

利用问题的形式 和 用户进行交互

var questions = [
  {type: 'input', name: 'productName', message: '请输入你的项目名/压缩文件名', 'store': true},
  {type: 'confirm', name: 'installNpm', message: '是否需要自动安装npm依赖', default: false, 'store': true}
];

this.prompt(questionlist).then(function (answers) {
        for (var key in answers) {
          config[key] = answers[key];
        }
        callback && callback();
})

prompt 由inquirerjs 提供

https://github.com/SBoudrias/Inquirer.js

Yeoman 扩展了 Inquirer.js API,通过加入了一个 store 属性去问对象。此属性允许您指定,用户提供的答案应该作为未来的默认答案使用。这可以如下做:

复制文件

this.fs.copyTpl(this.templatePath('_package.json'), this.destinationPath('package.json'), this.props);

this.fs 使用了 mem-fs editor 这个库 操作文件

https://github.com/sboudrias/mem-fs-editor

this.fs.copyTpl(from, to, data) 将from 利用 ejs模板引擎 编译之后复制到 to ,data传入ejs

this.templatePath('_package.json') 获取template 里面的_package.json 的路径

this.destinationPath('package.json') 目标文件路径

安装依赖

this.npmInstall();

实例和 code review

github.com/Lotuslwb/ge…