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的执行顺序是依次从上到下执行。

  

posted @ 2016-12-12 11:14  Ryan chen  阅读(386)  评论(0编辑  收藏  举报