yoman 创建generator

   yoman作为一个模板工具,能够创建自己的模板,下面具体介绍下。

   首先 安装一个模板工具(npm install -g generator-generator),此工具会自动创建一些必要的文件。安装完成后,yo generator 就行。

   最重要的一个文件就是generators中的index.js,生成器的所有逻辑都在此文件中。

   文件里面的日志输出,同一用this.log("");

   constructor

    在此构造函数里,通常用来定义命令行的参数。一般用不到,通过prompt交互更加友好。

   // Next, add your custom code

    this.option('coffee'); // This method adds support for a `--coffee` flag 这样就添加了一个coffee 命令行参数。
 prompting

    用来和client交互,控制台的输出:

    

this.log(yosay(
'Welcome to the magnificent ' + chalk.red('generator-ryanfirst') + ' generator!'
));
会在界面上显示:

 

prompting是个对象可以定义多个交互方法:

 1   prompting:{
 2     dir: function () {
 3 
 4       if (this.options.createDirectory !== undefined) {
 5         return true;
 6       }
 7       // Have Yeoman greet the user.
 8       this.log(yosay(
 9         'Welcome to the magnificent ' + chalk.red('generator-ryanfirst') + ' generator!'
10       ));
11 
12       var prompt = [{
13         type: 'confirm',
14         name: 'createDirectory',
15         message: 'Would you like to create a new directory for your project?'
16       }];
17 
18       return this.prompt(prompt).then(function (response) {
19         this.options.createDirectory = response.createDirectory;
20       }.bind(this));
21     },
22     dirname: function () {
23       if (!this.options.createDirectory || this.options.dirname) {
24         return true;
25       }
26 
27       var prompt = [{
28         type: 'input',
29         name: 'dirname',
30         message: 'Enter directory name'
31       }];
32 
33       return this.prompt(prompt).then(function (response) {
34         this.options.dirname = response.dirname;
35       }.bind(this));
36     }
37   }

这样就会有以下的输出

 

  writing

    主要的执行逻辑,创建文件和同步模板文件等。作为示例,仅仅做文件的同步:

 

1  if(this.options.createDirectory){
2       this.destinationRoot(this.options.dirname);
3       this.appname = this.options.dirname;
4     }
5     this.fs.copy(
6        this.templatePath('.'),
7 
8        this.destinationPath('.')
9     );

   如上,首先根据promt中的输入,创建文件夹,然后再同步所有的模板文件中的文件。

   install

   安装所有的依赖项。

   以上即是所有的主要方法,可自定义方法,输出需要信息。yoman的执行顺序是依次从上到下执行。

  

转载于:https://www.cnblogs.com/ryansecreat/p/6163737.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值