在 gulp 中为子文件夹执行命令

Excute command in gulp for sub folder

我的项目结构如下:

myapp
 -server.js
 -test
 --testcontent
 ---package.json
 -package.json

我有两个 package.json 文件,我想 运行 npm installtestcontent 文件夹内的 package.json 上。

如果在命令行中我转到 myapp/test/testcontent 和 运行 npm install 它会工作并且它会创建一个新文件夹 node_modules 以及来自正确 package.json。如何从 gulp 内部完成?

我尝试了以下但它使用 myapp 中的 package.json 而不是 testcontent 子文件夹中的那个:

gulp.task('default', function () {
    var options = {
        continueOnError: true, // default = false, true means don't emit error event
        pipeStdout: true, // default = false, true means stdout is written to file.contents
        customTemplatingThing: "test" // content passed to gutil.template()
    };
    var reportOptions = {
        err: true, // default = true, false means don't write err
        stderr: true, // default = true, false means don't write stderr
        stdout: true // default = true, false means don't write stdout
    }
    gulp.src('test/testcontent/')
        .pipe(exec('npm install' , options))
        .pipe(exec.reporter(reportOptions));
});

gulp-exec 是这项工作的错误工具。事实上,gulp-exec 插件的作者 explicitly advise 反对以您的方式使用它:

Note: If you just want to run a command, just run the command, don't use this plugin

而是使用 node.js 内置 child_process.spawn()。您可以使用 cwd 选项传递执行命令的目录:

var spawn = require('child_process').spawn;

gulp.task('default', function(done) {
  spawn('npm', ['install'], { cwd: 'test/testcontent/', stdio: 'inherit' })
    .on('close', done);
});