假设您有一个生成器generator-blog (BlogGenerator) 和两个子生成器(博客服务器和博客客户端):
app\index.js
client\index.js
server\index.js
所以当您运行yo blog 时,您应该向用户询问一些选项并运行(可选)子生成器,对吗?
要运行子生成器,您需要调用 this.invoke("generator_namespace", {options: {}})。
我们传递的第二个参数可以有options 字段——它是选项对象,它将被传递给生成器。
在 app\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}});
}
};
在客户端\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 日更新:
现在不推荐使用invoke,应将其替换为composeWith。但这并不像想象的那么容易。 invoke 和 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.Base替换的yeoman.generators.Base。