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的執行順序是依次從上到下執行。

相關文章
相關標籤/搜索