我正在构建一个自定义 Yeoman 生成器,它安装了许多预处理语言编译器,例如 CoffeeScript、LESS 和 Jade。在我的生成器创建的 Gruntfile 中,我有一个编译所有内容的构建任务。但是,在该构建任务至少运行一次之前,编译后的 HTML、CSS 和 Javascript 文件并不存在,如果我尝试在新搭建脚手架后运行 grunt watch/connect 服务器,这可能会令人困惑。
让我的生成器在安装结束时运行 Grunt 构建步骤的最佳方法是什么?已用于调用 this.installDependency
的 end
事件似乎是执行此操作的正确位置,但我应该如何与 Grunt 通信?
最佳答案
如果您遵循堆栈,this.installDependency
最终会下降到 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.installDependency
接受回调,因此您的代码可能如下所示:
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
调用之上添加一些错误处理以确保安全。
关于javascript - 如何在 Yeoman 生成器安装完成后运行 Grunt 任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18841273/