如果您遵循堆栈,this.installDependencies
最终会向下运行到https://github.com/yeoman/generator/blob/45258c0a48edfb917ecf915e842b091a26d17f3e/lib/actions/install.js#L36:
this.spawnCommand(installer, args, cb)
.on('error', cb)
.on('exit', this.emit.bind(this, installer + 'Install:end', paths))
.on('exit', function (err) {
if (err === 127) {
this.log.error('Could not find ' + installer + '. Please install with ' +
'`npm install -g ' + installer + '`.');
}
cb(err);
}.bind(this));
进一步追究这一点,this.spawnCommand
来自https://github.com/yeoman/generator/blob/master/lib/actions/spawn_command.js:
var spawn = require('child_process').spawn;
var win32 = process.platform === 'win32';
/**
* Normalize a command across OS and spawn it.
*
* @param {String} command
* @param {Array} args
*/
module.exports = function spawnCommand(command, args) {
var winCommand = win32 ? 'cmd' : command;
var winArgs = win32 ? ['/c'].concat(command, args) : args;
return spawn(winCommand, winArgs, { stdio: 'inherit' });
};
换句话说,在您的生成器代码中,您可以this.spawnCommand
随时调用,并将您希望终端运行的参数传递给它。如中,this.spawnCommand('grunt', ['build'])
。
那么下一个问题是你把它放在哪里?线性思考,你只能相信grunt build
在安装了所有依赖项之后它才会起作用。
从https://github.com/yeoman/generator/blob/45258c0a48edfb917ecf915e842b091a26d17f3e/lib/actions/install.js#L67-69接受回调,
this.installDependencies
因此您的代码可能如下所示:
this.on('end', function () {
this.installDependencies({
skipInstall: this.options['skip-install'],
callback: function () {
this.spawnCommand('grunt', ['build']);
}.bind(this) // bind the callback to the parent scope
});
});
试一试!this.spawnCommand
如果一切顺利,您应该在该新调用之上添加一些错误处理以确保安全。