IT

Gulp 작업에 매개 변수 전달

lottoking 2020. 5. 23. 09:21
반응형

Gulp 작업에 매개 변수 전달


일반적으로 콘솔에서 gulp 작업을 다음과 같은 방법으로 실행할 수 있습니다 gulp mytask. 어쨌든 gulp 작업에 매개 변수를 전달할 수 있습니까? 가능하면 어떻게 할 수 있는지 예를 보여주십시오.


없이는 프로그램을 유지할 수없는 기능입니다. yargs를 시도 할 수 있습니다.

npm install --save-dev yargs

다음과 같이 사용할 수 있습니다.

gulp mytask --production --test 1234

코드에서 예를 들면 다음과 같습니다.

var argv = require('yargs').argv;
var isProduction = (argv.production === undefined) ? false : true;

당신의 이해를 돕기 위해:

> gulp watch
console.log(argv.production === undefined);  <-- true
console.log(argv.test === undefined);        <-- true

> gulp watch --production
console.log(argv.production === undefined);  <-- false
console.log(argv.production);                <-- true
console.log(argv.test === undefined);        <-- true
console.log(argv.test);                      <-- undefined

> gulp watch --production --test 1234
console.log(argv.production === undefined);  <-- false
console.log(argv.production);                <-- true
console.log(argv.test === undefined);        <-- false
console.log(argv.test);                      <-- 1234

여기에서 가져갈 수 있기를 바랍니다.

사용할 수있는 또 다른 플러그인 인 minimist가 있습니다. yargs와 minimist에 대한 좋은 예가있는 또 다른 게시물이 있습니다. ( 다른 방법으로 작업을 실행하도록 Gulp에 플래그를 전달할 수 있습니까? )


추가 종속성을 추가하지 않으려면 노드 process.argv가 유용하다는 것을 알았습니다 .

gulp.task('mytask', function() {
    console.log(process.argv);
});

그래서 다음과 같이 :

gulp mytask --option 123

표시되어야합니다 :

[ 'node', 'path/to/gulp.js', 'mytask', '--option', '123']

원하는 매개 변수가 올바른 위치에 있다고 확신하면 플래그가 필요하지 않습니다. **이 경우 다음을 사용하십시오.

var option = process.argv[4]; //set to '123'

그러나 옵션이 설정되지 않았거나 다른 위치에있을 수 있으므로 더 나은 아이디어는 다음과 같습니다.

var option, i = process.argv.indexOf("--option");
if(i>-1) {
    option = process.argv[i+1];
}

이렇게하면 다음과 같은 여러 옵션의 변형을 처리 할 수 ​​있습니다.

//task should still find 'option' variable in all cases
gulp mytask --newoption somestuff --option 123
gulp mytask --option 123 --newoption somestuff
gulp mytask --flag --option 123

** 편집 : 노드 스크립트의 경우 true이지만 gulp는 앞에 "-"가없는 것을 다른 작업 이름으로 해석합니다. 따라서 gulp mytask 123gulp에서 '123'이라는 작업을 찾을 수 없으므로 사용 이 실패합니다.


꿀꺽 꿀꺽 매개 변수를 전달하면 몇 가지를 의미 할 수 있습니다.

  • 명령 행에서 gulpfile로 (이미 여기에 예시되어 있음)
  • gulpfile.js 스크립트의 본문에서 gulp 작업까지
  • 한 번의 과업에서 다른 과업으로.

Here's an approach of passing parameters from the main gulpfile to a gulp task. By moving the task that needs the parameter to it's own module and wrapping it in a function (so a parameter can be passed).:

// ./gulp-tasks/my-neat-task.js file
module.exports = function(opts){

  opts.gulp.task('my-neat-task', function(){
      console.log( 'the value is ' + opts.value );
  });

};

//main gulpfile.js file

//...do some work to figure out a value called val...
var val = 'some value';

//pass that value as a parameter to the 'my-neat-task' gulp task
require('./gulp-tasks/my-neat-task.js')({ gulp: gulp, value: val});

This can come in handy if you have a lot of gulp tasks and want to pass them some handy environmental configs. I'm not sure if it can work between one task and another.


There's an official gulp recipe for this using minimist.

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

The basics are using minimist to separate the cli arguments and combine them with known options:

var options = minimist(process.argv.slice(2), knownOptions);

Which would parse something like

$ gulp scripts --env development

More complete info in the recipe.


If you want to use environment params and other utils as well such as log, you can use gulp-util

/* 
  $npm install gulp-util --save-dev
  $gulp --varName 123
*/
var util = require('gulp-util');
util.log(util.env.varName);

@Ethan's answer would completely work. From my experience, the more node way is to use environment variables. It's a standard way to configure programs deployed on hosting platforms (e.g. Heroku or Dokku).

To pass the parameter from the command line, do it like this:

Development: gulp dev

Production: NODE_ENV=production gulp dev

The syntax is different, but very Unix, and it's compatible with Heroku, Dokku, etc.

You can access the variable in your code at process.env.NODE_ENV

MYAPP=something_else gulp dev

would set

process.env.MYAPP === 'something_else'

This answer might give you some other ideas.


Here is my sample how I use it. For the css/less task. Can be applied for all.

var cssTask = function (options) {
  var minifyCSS = require('gulp-minify-css'),
    less = require('gulp-less'),
    src = cssDependencies;

  src.push(codePath + '**/*.less');

  var run = function () {
    var start = Date.now();

    console.log('Start building CSS/LESS bundle');

    gulp.src(src)
      .pipe(gulpif(options.devBuild, plumber({
        errorHandler: onError
      })))
      .pipe(concat('main.css'))
      .pipe(less())
      .pipe(gulpif(options.minify, minifyCSS()))
      .pipe(gulp.dest(buildPath + 'css'))
      .pipe(gulpif(options.devBuild, browserSync.reload({stream:true})))
      .pipe(notify(function () {
        console.log('END CSS/LESS built in ' + (Date.now() - start) + 'ms');
      }));
  };

  run();

  if (options.watch) {
    gulp.watch(src, run);
  }
};

gulp.task('dev', function () {
  var options = {
    devBuild: true,
    minify: false,
    watch: false
  };

  cssTask (options);
});

Here is another way without extra modules:

I needed to guess the environment from the task name, I have a 'dev' task and a 'prod' task.

When I run gulp prod it should be set to prod environment. When I run gulp dev or anything else it should be set to dev environment.

For that I just check the running task name:

devEnv = process.argv[process.argv.length-1] !== 'prod';

If you use gulp with yargs, notice the following:

If you have a task 'customer' and wan't to use yargs build in Parameter checking for required commands:

.command("customer <place> [language]","Create a customer directory") call it with:

gulp customer --customer Bob --place Chicago --language english

yargs will allway throw an error, that there are not enough commands was assigned to the call, even if you have!! —

Give it a try and add only a digit to the command (to make it not equal to the gulp-task name)... and it will work:

.command("customer1 <place> [language]","Create a customer directory")

This is cause of gulp seems to trigger the task, before yargs is able to check for this required Parameter. It cost me surveral hours to figure this out.

Hope this helps you..


I know I am late to answer this question but I would like to add something to answer of @Ethan, the highest voted and accepted answer.

We can use yargs to get the command line parameter and with that we can also add our own alias for some parameters like follow.

var args = require('yargs')
    .alias('r', 'release')
    .alias('d', 'develop')
    .default('release', false)
    .argv;

Kindly refer this link for more details. https://github.com/yargs/yargs/blob/HEAD/docs/api.md

Following is use of alias as per given in documentation of yargs. We can also find more yargs function there and can make the command line passing experience even better.

.alias(key, alias)

Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa.

Optionally .alias() can take an object that maps keys to aliases. Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings.


Just load it into a new object on process .. process.gulp = {} and have the task look there.

참고URL : https://stackoverflow.com/questions/28538918/pass-parameter-to-gulp-task

반응형