假设您有一个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:
Usinginvoke
现在已弃用,应替换为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.generators.Base
为yeoman.Base
.