本文翻译自:Is it possible to pass a flag to Gulp to have it run tasks in different ways?

Normally in Gulp tasks look like this: 通常在Gulp任务中看起来像这样:

gulp.task('my-task', function() {return gulp.src(options.SCSS_SOURCE).pipe(sass({style:'nested'})).pipe(autoprefixer('last 10 version')).pipe(concat('style.css')).pipe(gulp.dest(options.SCSS_DEST));
});

Is it possible to pass a command line flag to gulp (that's not a task) and have it run tasks conditionally based on that? 是否可以将命令行标志传递给gulp(这不是一项任务)并让它根据它有条件地运行任务? For instance 例如

$ gulp my-task -a 1

And then in my gulpfile.js: 然后在我的gulpfile.js中:

gulp.task('my-task', function() {if (a == 1) {var source = options.SCSS_SOURCE;} else {var source = options.OTHER_SOURCE;}return gulp.src(source).pipe(sass({style:'nested'})).pipe(autoprefixer('last 10 version')).pipe(concat('style.css')).pipe(gulp.dest(options.SCSS_DEST));
});

#1楼

参考:https://stackoom.com/question/1YbVC/是否可以将标志传递给Gulp以使其以不同方式运行任务


#2楼

Gulp doesn't offer any kind of util for that, but you can use one of the many command args parsers. Gulp不提供任何类型的util,但你可以使用众多命令args解析器之一。 I like yargs . 我喜欢yargs Should be: 应该:

var argv = require('yargs').argv;gulp.task('my-task', function() {return gulp.src(argv.a == 1 ? options.SCSS_SOURCE : options.OTHER_SOURCE).pipe(sass({style:'nested'})).pipe(autoprefixer('last 10 version')).pipe(concat('style.css')).pipe(gulp.dest(options.SCSS_DEST));
});

You can also combine it with gulp-if to conditionally pipe the stream, very useful for dev vs. prod building: 您还可以将它与gulp-if以有条件地管道流,对于dev与prod构建非常有用:

var argv = require('yargs').argv,gulpif = require('gulp-if'),rename = require('gulp-rename'),uglify = require('gulp-uglify');gulp.task('my-js-task', function() {gulp.src('src/**/*.js').pipe(concat('out.js')).pipe(gulpif(argv.production, uglify())).pipe(gulpif(argv.production, rename({suffix: '.min'}))).pipe(gulp.dest('dist/'));
});

And call with gulp my-js-task or gulp my-js-task --production . 并使用gulp my-js-taskgulp my-js-task --production调用。


#3楼

Edit 编辑

gulp-util is deprecated and should be avoid, so it's recommended to use minimist instead, which gulp-util already used. gulp-util已被弃用 ,应该避免使用,因此建议使用minimalist , gulp gulp-util已经使用过。

So I've changed some lines in my gulpfile to remove gulp-util : 所以我在gulpfile中更改了一些行以删除gulp gulp-util

var argv = require('minimist')(process.argv.slice(2));gulp.task('styles', function() {return gulp.src(['src/styles/' + (argv.theme || 'main') + '.scss'])…
});

Original 原版的

In my project I use the following flag: 在我的项目中,我使用以下标志:

gulp styles --theme literature

Gulp offers an object gulp.env for that. Gulp gulp.env提供了一个对象gulp.env It's deprecated in newer versions, so you must use gulp-util for that. 它在较新版本中已被弃用,因此您必须使用gulp-util。 The tasks looks like this: 任务看起来像这样:

var util = require('gulp-util');gulp.task('styles', function() {return gulp.src(['src/styles/' + (util.env.theme ? util.env.theme : 'main') + '.scss']).pipe(compass({config_file: './config.rb',sass   : 'src/styles',css    : 'dist/styles',style  : 'expanded'})).pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'ff 17', 'opera 12.1', 'ios 6', 'android 4')).pipe(livereload(server)).pipe(gulp.dest('dist/styles')).pipe(notify({ message: 'Styles task complete' }));
});

The environment setting is available during all subtasks. 所有子任务期间都可以使用环境设置。 So I can use this flag on the watch task too: 所以我也可以在监视任务上使用这个标志:

gulp watch --theme literature

And my styles task also works. 我的风格任务也有效。

Ciao Ralf Ciao Ralf


#4楼

Here's a quick recipe I found: 这是我找到的快速配方:

gulpfile.js gulpfile.js

var gulp   = require('gulp');// npm install gulp yargs gulp-if gulp-uglify
var args   = require('yargs').argv;
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');var isProduction = args.env === 'production';gulp.task('scripts', function() {return gulp.src('**/*.js').pipe(gulpif(isProduction, uglify())) // only minify if production.pipe(gulp.dest('dist'));
});

CLI CLI

gulp scripts --env production

Original Ref (not available anymore): https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-params-from-cli.md Original Ref(不再提供): https : //github.com/gulpjs/gulp/blob/master/docs/recipes/pass-params-from-cli.md

Alternative with minimist 最小化的替代品

From Updated Ref: https://github.com/gulpjs/gulp/blob/master/docs/recipes/pass-arguments-from-cli.md 来自更新的参考: https : //github.com/gulpjs/gulp/blob/master/docs/recipes/pass-arguments-from-cli.md

gulpfile.js gulpfile.js

// npm install --save-dev gulp gulp-if gulp-uglify minimistvar gulp = require('gulp');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');var minimist = require('minimist');var knownOptions = {string: 'env',default: { env: process.env.NODE_ENV || 'production' }
};var options = minimist(process.argv.slice(2), knownOptions);gulp.task('scripts', function() {return gulp.src('**/*.js').pipe(gulpif(options.env === 'production', uglify())) // only minify if production.pipe(gulp.dest('dist'));
});

CLI CLI

gulp scripts --env production

#5楼

If you've some strict (ordered!) arguments, then you can get them simply by checking process.argv . 如果你有一些严格的(有序的!)参数,那么你可以通过检查process.argv来获得它们。

var args = process.argv.slice(2);if (args[0] === "--env" && args[1] === "production");

Execute it: gulp --env production 执行它: gulp --env production

...however, I think that this is tooo strict and not bulletproof! ...但是,我认为这严格而且不防弹! So, I fiddled a bit around... and ended up with this utility function: 所以,我摆弄了一下......最后得到了这个效用函数:

function getArg(key) {var index = process.argv.indexOf(key);var next = process.argv[index + 1];return (index < 0) ? null : (!next || next[0] === "-") ? true : next;
}

It eats an argument-name and will search for this in process.argv . 它吃了一个参数名称,并将在process.argv搜索它。 If nothing was found it spits out null . 如果没有找到任何内容,则会吐出null Otherwise if their is no next argument or the next argument is a command and not a value (we differ with a dash) true gets returned. 否则,如果它们没有下一个参数,或者下一个参数是一个命令而不是一个值(我们用破折号不同),则返回true (That's because the key exist, but there's just no value). (那是因为密钥存在,但没有价值)。 If all the cases before will fail, the next argument-value is what we get. 如果之前的所有情况都会失败,那么下一个参数值就是我们得到的。

> gulp watch --foo --bar 1337 -boom "Foo isn't equal to bar."

getArg("--foo") // => true
getArg("--bar") // => "1337"
getArg("-boom") // => "Foo isn't equal to bar."
getArg("--404") // => null

Ok, enough for now... Here's a simple example using gulp : 好的,现在已经足够......这是一个使用gulp的简单示例:

var gulp = require("gulp");
var sass = require("gulp-sass");
var rename = require("gulp-rename");var env = getArg("--env");gulp.task("styles", function () {return gulp.src("./index.scss").pipe(sass({style: env === "production" ? "compressed" : "nested"})).pipe(rename({extname: env === "production" ? ".min.css" : ".css"})).pipe(gulp.dest("./build"));
});

Run it gulp --env production 运行它gulp --env production


#6楼

There's a very simple way to do on/off flags without parsing the arguments. 有一种非常简单的方法可以on/off不解析参数的情况下执行on/off标志。 gulpfile.js is just a file that's executed like any other, so you can do: gulpfile.js只是一个像其他文件一样执行的文件,所以你可以这样做:

var flags = {production: false
};gulp.task('production', function () {flags.production = true;
});

And use something like gulp-if to conditionally execute a step 并使用gulp-if条件执行步骤

gulp.task('build', function () {gulp.src('*.html').pipe(gulp_if(flags.production, minify_html())).pipe(gulp.dest('build/'));
});

Executing gulp build will produce a nice html, while gulp production build will minify it. 执行gulp build将产生一个不错的html,而gulp production build将缩小它。

是否可以将标志传递给Gulp以使其以不同方式运行任务?相关推荐

  1. 如何将命令行参数传递给Node.js程序?

    我有一个用Node.js编写的Web服务器,我想使用一个特定的文件夹启动. 我不确定如何在JavaScript中访问参数. 我正在像这样运行节点: $ node server.js folder 这是 ...

  2. python中forward的参数_如何将关键字参数传递给preforward钩子使用的forward?

    Torchscript不兼容(截至1.2.0) 首先,您的示例torch.nn.Module有一些小错误(可能是意外造成的).在 第二,您可以将任何传递给forward,register_forwar ...

  3. 通过BeanShell获取UUID并将参数传递给Jmeter

    有些HTTPS请求报文的报文体中包含由客户端生成的UUID,在用Jmeter做接口自动化测试的时候,因为越过了客户端,直接向服务器端发送报文,所以,需要在Jmeter中通过beanshell获取UUI ...

  4. jqgrid ajax 请求参数,如何将csrf_令牌传递给jqgrid的editurl的post参数?

    我在Django框架中使用JqGrid.这是JS:jQuery("#list").jqGrid({ url:'{% url views.manage.devicesajax %}' ...

  5. java矩阵传递给r_从JAVA调用R得到卡方统计和p值

    我在JAVA中有两个4 * 4矩阵,其中一个矩阵包含观察计数和其他预期计数. 我需要一种自动的方法来计算这两个矩阵之间的卡方统计量的p值; 但是,就我所知,JAVA没有这样的功能. 我可以通过将两个矩 ...

  6. java+hadoop配置参数_将Hadoop参数传递给Java代码

    我有一个Uber jar执行一些级联ETL任务. jar的执行方式如下: hadoop jar munge-data.jar 我希望在作业启动时将参数传递给jar,例如 hadoop jar mung ...

  7. 检查传递给Bash脚本的参数数量

    本文翻译自:Check number of arguments passed to a Bash script I would like my Bash script to print an erro ...

  8. linux make 命令行 定义宏(-D)传递给C源代码 简介

    需求: 通常使用 -dname=值 从"make命令行"传递给"makefile". 该定义可在makefile中访问. 想使用 编译器选项 将宏定义从&quo ...

  9. html表单文本框怎么输出函数值,如何获取用户输入的html文本表单字段传递给javascript函数的值?...

    我想通过生成用户必须输入到文本输入表单字段的随机数创建我自己的反垃圾邮件过滤器,如果它是正确的,他们进入下一页,如果不是,则显示错误数字输入不正确.如何获取用户输入的html文本表单字段传递给java ...

最新文章

  1. 遍历数据键和值 php,php数组实例之获取当前数组键和值 each()
  2. shell学习笔记 (2)
  3. A Network-based End-to-End Trainable Task-oriented Dialogue System
  4. arouter跨module传递消息_消息队列中间件(二)使用 ActiveMQ
  5. java 对象被回收的例子_jvm(4)---垃圾回收(哪些对象可以被回收)
  6. 服务器有效设置防止web入侵
  7. 再读《Java编程思想 》
  8. 比例电磁阀(零)液压知识
  9. 6自由度机械臂的建立
  10. 淘宝客升级助手V1.0 等级升级获取高级账户,淘客适用高佣金破解版
  11. C语言排序函数qsort用法
  12. H.264中多参考帧预测技术的优化
  13. oneNote笔记名不同步
  14. 好用的parallel命令
  15. Nginx 安全漏洞
  16. 连接板卡的时候,如何避免每次都设置ip
  17. 全面解读Moby和LinuxKit,Docker称沟通不善招致误解
  18. 关于苹果手机打开钉钉小程序中处理的日期显示invalid date
  19. java 字符串长度 ascii_将Unicode转换为ASCII而不更改字符串长度(在Java中)
  20. MC9S12XS128硬件底层驱动_set_bus_clk.h(总线时钟设置)

热门文章

  1. Android开发之使用Handler封装下载图片工具类(源代码分享)
  2. AMS重要的数据结构解析(三):ActivityStack
  3. 关于openGL学习心得
  4. Android NDK开发之旅(2):一篇文章搞定Android Studio中使用CMake进行NDK/JNI开发
  5. Broadcast应用场景分析
  6. Android应用点击两次back退出
  7. java解析getresponsebodyasstring_java读取网站内容的两种方法是什么呢?
  8. sonar:查询全部项目的bug和漏洞总数(只查询阻断/严重/主要级别)
  9. Java NIO.2 Files类的常用方法
  10. 跟老齐学Python:轻松入门pdf