Prompts是主要和用戶交互的方式。prompt方法是異步的,並返回一個promise。你須要從task中返回promise,以便在運行下一個任務以前等待任務完成web
module.exports = class extends Generator { async prompting() { const answers = await this.prompt([ { type: "input", name: "name", message: "Your project name", default: this.appname // Default to current folder name }, { type: "confirm", name: "cool", message: "Would you like to enable the Cool feature?" } ]); this.log("app name", answers.name); this.log("cool feature", answers.cool); } };
module.exports = class extends Generator { async prompting() { this.answers = await this.prompt([ { type: "confirm", name: "cool", message: "Would you like to enable the Cool feature?" } ]); } writing() { this.log("cool feature", this.answers.cool); // user answer `cool` used } };
用戶在一些選項可能會每次都選擇相同的,對於這種狀況咱們比較好的作法是記住用戶的輸入,而且在下一次做爲默認的選項。segmentfault
this.prompt({ type: "input", name: "username", message: "What's your GitHub username", store: true //肯定是否存儲用戶的輸入 });
Arguments 能夠經過命令行傳輸promise
yo webapp my-project //my-project 是第一個參數
告知系統咱們須要參數能夠用 this.argument()方法,接受name(string)和一個對象爲參數app
獲取這個name的方式能夠用:this.options[name].webapp
可選傳入對象參數:異步
this.argument必須在constructor中調用。不然,當用戶使用help選項調用生成器時,Yeoman將沒法輸出相關的幫助信息:例如yowebapp--help。async
module.exports = class extends Generator { // note: arguments and options should be defined in the constructor. constructor(args, opts) { super(args, opts); // This makes `appname` a required argument. this.argument("appname", { type: String, required: true }); // And you can then access it later; e.g. this.log(this.options.appname); } };
Options和arguments看着很像,但它們是做爲命令行標誌編寫的。ide
yo webapp --coffee
this.option()這個方法能夠告訴系統咱們須要options,傳參方式和arguments同樣函數
可選傳入對象參數:工具
module.exports = class extends Generator { // note: arguments and options should be defined in the constructor. constructor(args, opts) { super(args, opts); // This method adds support for a `--coffee` flag this.option("coffee"); // And you can then access it later; e.g. this.scriptSuffix = this.options.coffee ? ".coffee" : ".js"; } };
輸出信息是由this.log 處理的信息,能夠在終端打印輸出信息
module.exports = class extends Generator { myAction() { this.log("Something has gone wrong!"); } };