Ответ 1
Предположим, у вас есть генератор generator-blog
(BlogGenerator) с двумя подгенераторами (blog-server и blog-client):
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}});
}
};
В клиенте \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.generators.Base
на yeoman.Base
.