假设您有一台发电机generator-blog
(BlogGenerator) 有两个子生成器(博客服务器和博客客户端):
app\index.js
client\index.js
server\index.js
所以当你跑步时yo blog
你应该向用户询问一些选项并运行(可选)子生成器,对吧?
要运行子生成器,您需要调用this.invoke("generator_namespace", {options: {}})
。
我们传递的第二个参数可以有options
字段 - 它是将传递给生成器的选项对象。
在应用程序\index.js中:
BlogGenerator.prototype.askFor = function askFor() {
var cb = this.async();
// have Yeoman greet the user.
console.log(this.yeoman);
var prompts = [{
name: 'appName',
message: 'Enter your app name',
default: 'MyBlog'
}, {
type: 'confirm',
name: 'createServer',
message: 'Would you like to create server project?',
default: true
}, {
type: 'confirm',
name: 'createClient',
message: 'Whould you like to create client project?',
default: true
}];
this.prompt(prompts, function (props) {
this.appName = props.appName;
this.createServer = props.createServer;
this.createClient = props.createClient;
cb();
}.bind(this));
}
BlogGenerator.prototype.main = function app() {
if (this.createClient) {
// Here: we'are calling the nested generator (via 'invoke' with options)
this.invoke("blog:client", {options: {nested: true, appName: this.appName}});
}
if (this.createServer) {
this.invoke("blog:server", {options: {nested: true, appName: this.appName}});
}
};
在 client\index.js 中:
var BlogGenerator = module.exports = function BlogGenerator(args, options, config) {
var that = this;
yeoman.Base.apply(this, arguments);
// in this.options we have the object passed to 'invoke' in app/index.js:
this.appName = that.options.appName;
this.nested = that.options.nested;
};
BlogGenerator .prototype.askFor = function askFor() {
var cb = this.async();
if (!this.options.nested) {
console.log(this.yeoman);
}
}
更新2015-12-21:
Using invoke
现已弃用,应替换为composeWith
。但这并不那么容易。之间的主要区别invoke
and composeWith
是现在你没有能力控制子发电机了。您只能声明使用它们。
就是这样main
上面的方法应该如下所示:
BlogGenerator.prototype.main = function app() {
if (this.createClient) {
this.composeWith("blog:client", {
options: {
nested: true,
appName: this.appName
}
}, {
local: require.resolve("./../client")
});
}
if (this.createServer) {
this.composeWith("blog:server", {
options: {
nested: true,
appName: this.appName
}
}, {
local: require.resolve("./../server")
});
}
};
我也删除了替换yeoman.generators.Base
with yeoman.Base
.