使用grunt自动执行npm和安装
Automate npm and bower install with grunt
我有一个node/angular项目,它使用npm进行后端依赖管理,使用bower进行前端依赖管理。我想使用grunt任务来执行这两个安装命令。我还没能想出怎么做这件事。
我尝试使用exec
,但是它实际上没有安装任何东西。
module.exports = function(grunt) {
grunt.registerTask('install', 'install the backend and frontend dependencies', function() {
// adapted from http://www.dzone.com/snippets/execute-unix-command-nodejs
var exec = require('child_process').exec,
sys = require('sys');
function puts(error, stdout, stderr) { console.log(stdout); sys.puts(stdout) }
// assuming this command is run from the root of the repo
exec('bower install', {cwd: './frontend'}, puts);
});
};
当我cd
进入前端,打开node
,并从控制台运行此代码,这工作得很好。我在任务中做错了什么?
(我也尝试过使用bower和npm的api,但也不能使其工作)
要在npm install
期间同时安装客户端组件而不是服务器端库,您可以添加package.json
"dependencies": {
...
"bower" : ""
},
"scripts": {
...
"postinstall" : "bower install"
}
我更喜欢区分install和test/build
你需要告诉grunt你正在使用一个异步方法(.exec
),通过调用this.async()
方法,获得一个回调,并在exec完成时调用它。
这个应该可以工作:
module.exports = function(grunt) {
grunt.registerTask('install', 'install the backend and frontend dependencies', function() {
var exec = require('child_process').exec;
var cb = this.async();
exec('bower install', {cwd: './frontend'}, function(err, stdout, stderr) {
console.log(stdout);
cb();
});
});
};
参见为什么我的异步任务没有完成?
仅供参考,这是我现在的位置。
你也可以用另一种方式解决这个问题,比如让npm处理wer的执行,最终让grunt处理npm。
grunt.registerTask('install', 'install the backend and frontend dependencies', function() {
var async = require('async');
var exec = require('child_process').exec;
var done = this.async();
var runCmd = function(item, callback) {
process.stdout.write('running "' + item + '"...'n');
var cmd = exec(item);
cmd.stdout.on('data', function (data) {
grunt.log.writeln(data);
});
cmd.stderr.on('data', function (data) {
grunt.log.errorlns(data);
});
cmd.on('exit', function (code) {
if (code !== 0) throw new Error(item + ' failed');
grunt.log.writeln('done'n');
callback();
});
};
async.series({
npm: function(callback){
runCmd('npm install', callback);
},
bower: function(callback){
runCmd('bower install', callback);
}
},
function(err, results) {
if (err) done(false);
done();
});
});
执行此任务的Grunt任务(根据上面的Sindre的解决方案):
https://github.com/ahutchings/grunt-install-dependencies执行wer install命令的Grunt任务:https://github.com/yatskevich/grunt-bower-task
也可以使用https://github.com/stephenplusplus/grunt-bower-install
自动注入你的依赖到index.html文件
相关文章:
- 使用optimit.js文件中的npm安装optimize
- 如何让我的ember.js应用程序导入从bower或npm安装的模块
- npm安装can'找不到新版本
- npm安装vs sudo npm安装-g
- 使用 AWS Lambda 进行 npm 安装
- Npm 安装中出错
- npm 安装时出错
- 使用 npm 安装库
- 如何在 npm 安装期间将分叉存储库更新为依赖项
- 节点.js npm 安装错误
- 如何使用 npm 安装需要浏览器的 JS
- 我们将 npm 安装的节点模块放在 Meteor 项目中的什么位置
- 是否有最小版本的“npm 安装咕噜声”
- 如果我使用“npm install --save-dev”进行 NPM 安装,我该如何检查更新
- 如何使用 npm 安装的铯浏览器
- 是否可以在每个 npm 安装事件上运行一些脚本
- npm 安装是否也会构建库
- 节点.js npm 安装错误连接超时
- 如何使用 NPM 安装 socket.io 与 TypeScript 和 webpack 一起使用
- npm安装指向哪个主机名