使用grunt自动执行npm和安装

Automate npm and bower install with grunt

本文关键字:npm 安装 执行 grunt 使用      更新时间:2023-09-26

我有一个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文件