yoman 建立generator

   yoman做为一个模板工具,可以建立本身的模板,下面具体介绍下。npm

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

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

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

   constructor

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

   // Next, add your custom codespa

 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   }

这样就会有如下的输出code

 

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

相关文章
相关标签/搜索