【问题标题】:Excute command in gulp for sub folder在 gulp 中为子文件夹执行命令
【发布时间】:2016-07-24 10:17:08
【问题描述】:

我的项目结构如下:

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

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

如果在命令行中我转到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));
});

【问题讨论】:

    标签: node.js gulp child-process npm-install


    【解决方案1】:

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

    注意:如果你只是想运行一个命令,只运行命令,不要使用这个插件

    改为使用 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);
    });
    

    【讨论】:

    • 谢谢,那么我如何将它通过管道传输到其他进程?可以说我想像这样通过管道返回 gulp .src(config.alljs) .pipe($.if(args.verbose, $.打印()))
    • 你是什么意思“管道它到另一个进程”?您想将“npm install”的标准输出发送到另一个进程吗?你到底想做什么?
    • 你的例子没有意义。打印文件名与执行“npm install”有什么关系?两者完全没有关系。
    • 例如,如果你想做 npm install 并且还想复制文件等,你会怎么做?
    • 您编写了一项任务来复制文件和一项任务来执行“npm install”。然后你执行这两个任务。由于这两个操作完全没有共同点,它们应该在不同的任务中。
    猜你喜欢
    • 1970-01-01
    • 2012-11-24
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多