Send arguments to gulp task

2020-07-29 00:31发布

There are other questions on stackoverflow about this topic, but not the one I was hoping for.

Here is a simplified version of my gulpfile.js

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('css', function() {
    gulp.src('site/scss/style.scss')
        .pipe(sass())
        .pipe(gulp.dest('assets/css'))
});

gulp.task('watch', function() {
    gulp.watch('site/scss/**/*.scss', ['css']);
});

I can do this successfully:

gulp watch

Now I want to be able to do something like this in my terminal command line:

gulp watch my-domain-name

or

gulp watch my-other-domain

My gulpfile would in my mind look something like this:

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('css', function(name) {
    gulp.src('site/scss/style.scss')
        .pipe(sass())
        .pipe(gulp.dest('assets/css'))
});

gulp.task('watch', function(name) {
    gulp.watch('site/scss/**/*.scss', ['css', name]);
});

I try to send name around as a variable of my watch task. In my case it would be my-domain-name or my-other-domain depending on what I write in my terminal.

How can I send a parameter from the terminal to the watch task and then over to the css task?

1条回答
小情绪 Triste *
2楼-- · 2020-07-29 01:03

There are a number of sources for passing parameters from the command line to gulp. See:

https://www.sitepoint.com/pass-parameters-gulp-tasks/

https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-arguments-from-cli.md

The official recipe uses minimist an extremely popular package.

So with these approaches you would not be passing the command line args directly to the watch task, but rather to an object that can be accessed by any task.

And it look like gulp-param may do exactly what you want, directly injecting command line args into each task's callback function.

查看更多
登录 后发表回答