I'm trying to compress my project using gulp-uglify, however gulp seems to throw the error Unexpected token: punc () whenever it encounters an arrow function in the code. Is there anything I can do to fix this? Thank you.
gulp-crash-test.js
// Function with callback to simulate the real code
function test(callback) {
if (typeof callback === "function") callback();
}
// Causes a crash
test(() => {
console.log("Test ran successfully!");
});
// Doesn't cause a crash
test(function () {
console.log("Test ran successfully!");
});
gulpfile.js
var gulp = require("gulp");
var concat = require("gulp-concat");
var uglify = require("gulp-uglify");
gulp.task("scripts", function() {
gulp.src([
"./gulp-crash-test.js"
]).pipe(
concat("gulp-crash-test.min.js")
).pipe(
uglify().on('error', function(e){
console.log(e);
})
).pipe(
gulp.dest("./")
);
});
gulp.task("watch", function() {
gulp.watch("./gulp-crash-test.js", ["scripts"]);
});
gulp.task("default", ["watch", "scripts"]);
Arrow functions are an ES6 feature. Babel (and others) are designed to translate ES6 to ES5 or earlier as part of your build process. Luckily there are Babel plug-ins for Gulp and Grunt. Run Babel before uglify.
https://www.npmjs.com/package/gulp-babel
I hope this steers you in the right direction/somebody can demonstrate some code.
There is no supporting ugilify(minify) tools for ES6 Syntax.
you should be build gulp task after babel compile (es6 -> es5)
1.Install packages
npm install gulp-babel babel-preset-es2015
2.change your code as below.
var gulp = require("gulp");
var concat = require("gulp-concat");
var uglify = require("gulp-uglify");
var babel = require('gulp-babel');
gulp.task("scripts", function() {
return gulp.src(["./gulp-crash-test.js"])
.pipe(babel({presets: ['es2015']}))
.pipe(concat("gulp-crash-test.minjs"))
.pipe(uglify().on('error', function(e){
console.log(e);
}))
.pipe(gulp.dest("./"))
});
You can use babel minify (previously Babili) a library based on babel to minify ES6 code without transpiling:
First install via npm:
npm install --save-dev babel-preset-minify
Then in your gulp file:
var gulp = require('gulp')
var babel = require('gulp-babel')
gulp.task('default', () => {
return gulp.src('src/app.js')
.pipe(babel({presets: ['minify']}))
.pipe(gulp.dest('dist'))
})
It uses babel as a parser, but there is no transpilation.
I tried babeli it kinda sucked. build time took me 40s. And I am not looking to transpile the code into es5 anyway
I prefer using uglify-es follow the descriptions
https://www.npmjs.com/package/uglify-es
https://www.npmjs.com/package/gulp-uglify
My build times are now 10s. I have the patience to wait 10s.
This is my gulpfile
var gulp = require('gulp');
var uglifycss = require('gulp-uglifycss');
var htmlminifier = require('gulp-html-minifier');
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var clean = require('gulp-clean');
var uglifyes = require('uglify-es');
var composer = require('gulp-uglify/composer');
var minifyes = composer(uglifyes, console);
.pipe(gulpif('*.js', minifyes()))
This is what i use for useref with angular and babel.
gulp.task('concat-js', ['your dependency task'],function(){
return gulp.src('dev/dev_index/index.html')
.pipe(useref())
.pipe(gulpif('*.js', ngAnnotate())) // if you use angular
.pipe(gulpif('*.js',babel({
compact: false,
presets: [['es2015', {modules: false}]]
})))
.pipe(gulpif('*.js', uglify({ compress: false })
.pipe(gulp.dest('./'));
});
first 'babel' the .js file
var babel = require('gulp-babel');
gulp.task('babel-js', () =>
gulp.src('js/main.js')
.pipe(babel({presets: ['env']}))
.pipe(gulp.dest('build/babel'))
);
https://www.npmjs.com/package/gulp-babel
than 'uglify' it
var uglify = require('gulp-uglify'), pump = require('pump');
gulp.task('uglify-js', function (cb) {
pump([
gulp.src('build/babel/main.js'),
uglify(),
gulp.dest('build/js')
],
cb
);
});
https://www.npmjs.com/package/gulp-uglify
To be installed
npm install --save-dev gulp-babel babel-core babel-preset-env
npm install uglify-es -g
npm install pump
Related
I am trying to minify my script files for which i am using gulp task runner
And I am trying gulp-uglify plugin
Code:
gulp.task('concat', function() {
return gulp.src('app/**/*.js')
// .pipe(concat('script.js'))
.pipe(uglify())
.pipe(gulp.dest('./dist/'))
});
but i am getting error as
when i try to run gulp task as gulp concat
Any help would be appreciated
The main error is generated when you're using ES6 format. Use the gulp-uglify-es module instead of 'gulp-uglify' to overcome this error.
var uglify = require('gulp-uglify-es').default;
Note: gulp-uglify-es is no longer being maintained. You may want to use terser/gulp-terser instead:
To see the error in console:
var gutil = require('gulp-util');
gulp.task('concat', function() {
return gulp.src('app/**/*.js')
// .pipe(concat('script.js'))
.pipe(uglify())
.on('error', function (err) { gutil.log(gutil.colors.red('[Error]'), err.toString()); })
.pipe(gulp.dest('./dist/'))
});
To find the exact file, with line number of error register and run this task:
var pump = require('pump');
gulp.task('uglify-error-debugging', function (cb) {
pump([
gulp.src('app/**/*.js'),
uglify(),
gulp.dest('./dist/')
], cb);
});
I think the top answers here are not explaining how to get the error. The docs have a section on error handling:
gulp-uglify emits an 'error' event if it is unable to minify a
specific file
So, just capture the error and do whatever you want with it (such as logging to console) to see the filename, line number, and additional info:
uglify().on('error', console.error)
or in a larger context:
gulp.task('foo', () => {
return gulp.src([
'asset/src/js/foo/*.js',
'asset/src/js/bar/*.js',
])
.pipe(uglify().on('error', console.error))
.pipe(concat('bundle.js'))
.pipe(gulp.dest('./'));
});
This gives you a super helpful error!
{ GulpUglifyError: unable to minify JavaScript
at [stack trace])
cause:
{ SyntaxError: Continue not inside a loop or switch
[stack trace]
message: 'Continue not inside a loop or switch',
filename: 'ProductForm.js',
line: 301,
col: 37,
pos: 10331 },
plugin: 'gulp-uglify',
fileName:
'/asset/src/js/foo/ProductForm.js',
showStack: false }
Have you used ES6 format in your script file?
If so try ES5 now because when you do gulp-uglify it doesnt understand ES6 format as of now
and after that try your code
gulp.task('concat', function() {
return gulp.src('app/**/*.js')
.pipe(concat('script.js'))
.pipe(uglify())
.pipe(gulp.dest('./dist/'))
});
and run the task gulp concat it will work
For me, it was a deprecated option "preserveComments" that generated the error (and completely crashed the script).
Found the issue using:
gulp.task('concat', function() {
return gulp.src('app/**/*.js')
.pipe(uglify())
.on('error', function (err) { console.log( err ) })
.pipe(gulp.dest('./dist/'))
});
Try using this
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var minifyJS = require('gulp-minify');
gulp.task('concat', function() {
return gulp.src('app/**/*.js')
.pipe(minifyJS())
.pipe(concat('bundle.min.js'))
.pipe(uglify({ mangle: false }))
.pipe(gulp.dest('./dist/'));
});
you may have syntax error or used ES6 syntax. you can try https://skalman.github.io/UglifyJS-online/ firstly.
The main error to Unable to minifies JavaScript is the path not found. You can use the task usemin For this you need:
$ sudo npm install gulp-usemin --save-dev
$ sudo npm install gulp-livereload --save-dev
$ sudo npm install gulp-util --save-dev
and requires :
var usemin = require('gulp-usemin');
var livereload = require('gulp-livereload');
var gutil = require('gulp-util'); //gutil for error display
gulp.task('usemin',['jshint'], function(){
return gulp.src('./app/index.html')
.pipe(usemin({
css: [minifycss(),rev()],
scripts: [uglify().on('error', function(err) {gutil.log(gutil.colors.red('[Error]'), err.toString());this.emit('end');}),rev()]
}))
.pipe(gulp.dest('dist'))
.pipe(livereload());
});
Change the js: [uglify(), rev()] to scripts: [uglify(), rev()]
I'm attempting to use browser-sync with Gulp 4, but bs is not preserving state, and instead does a full refresh. This is not very useful. It seems bs no longer supports true injection. I filed an issue on GH if you want to contribute.
Here is the pertinent code:
// styles:dev task
gulp.task('styles:dev', function() {
return gulp.src(config.src)
.pipe(sourcemaps.init())
.pipe(postcss(config.postcss.dev))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(config.dest.dev))
.pipe(browserSync.stream());
});
// browserSync task
gulp.task('browserSync', function(cb) {
browserSync.init(config, cb);
});
// Watch task:
gulp.task('watch:styles', function() {
return gulp.watch(config.paths.css,
gulp.series('styles:dev'));
});
gulp.task('watch', gulp.parallel('watch:styles'));
// default task
gulp.task('default',
gulp.series('clean:dev',
gulp.parallel('copy:dev', 'styles:dev'), 'browserSync', 'watch')
);
Thanks in advance.
Fixed. Here's where I went wrong:
The browser-sync constructor takes an options object, which can include a files array. Most of the tutorials I've read, including the gulpfile for Google's very own Web Starter Kit, do not include this. As it turns out, this is required for style injection to preserve state.
Furthermore, do not pass .stream() or .reload() as the final pipe in your styles task. It is not needed, and will short circuit style injection, forcing a full refresh.
Finally, the browserSync process must not be terminated, and watch and browserSync tasks must execute in parallel in order for live style injection to take place.
Hope this helps anybody facing this issue.
I also closed the corresponding github issue, and posted my gulpfile
Almost 3 years later Gulp 4 now looks a little bit different, see https://gulpjs.com/docs/en/getting-started/creating-tasks
To have a complete Gulp 4 kickstart example, see https://gist.github.com/leymannx/8f6a75e8ad5055276a71d2901813726e
// Requires Gulp v4.
// $ npm uninstall --global gulp gulp-cli
// $ rm /usr/local/share/man/man1/gulp.1
// $ npm install --global gulp-cli
// $ npm install
const { src, dest, watch, series, parallel } = require('gulp');
const browsersync = require('browser-sync').create();
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const sourcemaps = require('gulp-sourcemaps');
const plumber = require('gulp-plumber');
const sasslint = require('gulp-sass-lint');
const cache = require('gulp-cached');
// Compile CSS from Sass.
function buildStyles() {
return src('scss/ix_experience.scss')
.pipe(plumber()) // Global error listener.
.pipe(sourcemaps.init())
.pipe(sass({ outputStyle: 'compressed' }))
.pipe(autoprefixer(['last 15 versions', '> 1%', 'ie 8', 'ie 7']))
.pipe(sourcemaps.write())
.pipe(dest('css/'))
.pipe(browsersync.reload({ stream: true }));
}
// Watch changes on all *.scss files, lint them and
// trigger buildStyles() at the end.
function watchFiles() {
watch(
['scss/*.scss', 'scss/**/*.scss'],
{ events: 'all', ignoreInitial: false },
series(sassLint, buildStyles)
);
}
// Init BrowserSync.
function browserSync(done) {
browsersync.init({
proxy: 'blog.localhost', // Change this value to match your local URL.
socket: {
domain: 'localhost:3000'
}
});
done();
}
// Init Sass linter.
function sassLint() {
return src(['scss/*.scss', 'scss/**/*.scss'])
.pipe(cache('sasslint'))
.pipe(sasslint({
configFile: '.sass-lint.yml'
}))
.pipe(sasslint.format())
.pipe(sasslint.failOnError());
}
// Export commands.
exports.default = parallel(browserSync, watchFiles); // $ gulp
exports.sass = buildStyles; // $ gulp sass
exports.watch = watchFiles; // $ gulp watch
exports.build = series(buildStyles); // $ gulp build
Goal
I'm updating my old gulpfile.js, which used to be mainly for compiling my Sass into CSS, but now I'm trying to get Gulp to do the following:
Sync browser, whip up localhost server - DONE
Compile Sass => CSS - DONE
Show any JavaScript errors with JSHint - DONE
Compile ES6 => ES6 with Babel (WORKING ON)
Minify all assets (WORKING ON)
Show project file size - DONE
Deploy index.html, style.css and images to S3 (WORKING ON)
Watch files, reload browser when .scss or .html changes - DONE
Problem
Trying to minify my Javascript and also create a scripts.min.js
file, it keeps adding the suffix min to every new minified JavaScript
file.
Folder structure
index.html
gulpfile.js
package.json
.aws.json
.csscomb.json
.gitignore
assets
- css
style.css
style.scss
--partials
---base
---components
---modules
- img
- js
scripts.js
- dist
gulpfile.js
// Include Gulp
var gulp = require('gulp');
var postcss = require("gulp-postcss");
// All of your plugins
var autoprefixer = require('autoprefixer');
var browserSync = require('browser-sync');
var cache = require('gulp-cache');
var concat = require('gulp-concat');
var csswring = require("csswring");
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lost = require("lost");
var plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var rucksack = require("rucksack-css");
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
// Sync browser, whip up server
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
// Reload page automagically
gulp.task('bs-reload', function () {
browserSync.reload();
});
// Compile Sass into CSS, apply postprocessors
gulp.task('styles', function(){
var processors = [
autoprefixer({browsers: ['last 2 version']}),
csswring,
lost,
rucksack
];
gulp.src(['assets/css/**/*.scss'])
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(sass())
.pipe(postcss(processors))
// .pipe(gulp.dest('assets/css/'))
// .pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('assets/css/'))
.pipe(browserSync.reload({stream:true}))
});
// Show any JavaScript errors
gulp.task('scripts', function(){
return gulp.src('assets/js/**/*.js')
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(jshint())
.pipe(jshint.reporter('default'))
// .pipe(concat('main.js'))
// .pipe(babel())
.pipe(gulp.dest('assets/js/'))
.pipe(uglify())
.pipe(gulp.dest('assets/js/'))
.pipe(rename({suffix: '.min'}))
.pipe(browserSync.reload({stream:true}))
});
// Minify assets, create build folder
gulp.task('images', function(){
gulp.src('assets/img/**/*')
.pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
.pipe(gulp.dest('assets/img'));
});
// Minify HTML
// Default task
gulp.task('default', ['browser-sync'], function(){
gulp.watch("assets/css/**/*.scss", ['styles']);
gulp.watch("assets/js/**/*.js", ['scripts']);
gulp.watch("*.html", ['bs-reload']);
gulp.start("images", "styles", "scripts")
});
// var babel = require('gulp-babel');
// var minifyhtml = require("gulp-minify-html");
// var size = require("gulp-size");
// var upload = require("gulp-s3");
Hi i can't solve all your problems but I had also a similar issue with the babel and ES6 fat arrow functions (using babelify and browserify). To solve the problem try to pass:
stage: 0
to your babel.js gulp plugin. If error will still occurs then try to pass also:
experimental: true
For more information please have a look "experimental" section on babel.js site.
I'm trying to create a gulp task with browserify and babelify. Here is the task:
var gulp = require('gulp');
var browserify = require('gulp-browserify');
var source = require('vinyl-source-stream');
var babelify = require('babelify');
gulp.task('js', function () {
browserify('./resources/js/*.js')
.transform(babelify)
.bundle()
.pipe(source('*.js'))
.pipe(gulp.dest('./public/js'));
});
I found a few sample code, tried to use them, but the result was always the same.
When i run the task, and save my example.js file, the following error occurs:
TypeError: browserify(...).transform is not a function
What am I doing wrong?
You're mixing up the API for browserify and gulp-browserify.
From the gulp-browserify docs, you'll want to do something like this:
var gulp = require('gulp')
var browserify = require('gulp-browserify')
gulp.task('js', function () {
gulp.src('./resources/js/*.js')
.pipe(browserify({
transform: ['babelify'],
}))
.pipe(gulp.dest('./public/js'))
});
EDIT: Since this question was first answered, gulp-browserify has been abandoned and gulp has evolved a great deal. If you'd like to achieve the same thing with a newer version of gulp, you can follow the guides provided by the gulp team.
You'll end up with something like the following:
var browserify = require('browserify');
var babelify = require('babelify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var sourcemaps = require('gulp-sourcemaps');
var util = require('gulp-util');
gulp.task('default', function () {
var b = browserify({
entries: './resources/test.js',
debug: true,
transform: [babelify.configure({
presets: ['es2015']
})]
});
return b.bundle()
.pipe(source('./resources/test.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
// Add other gulp transformations (eg. uglify) to the pipeline here.
.on('error', util.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/js/'));
});
Normally in Gulp tasks look like this:
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? For instance
$ gulp my-task -a 1
And then in my 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));
});
Gulp doesn't offer any kind of util for that, but you can use one of the many command args parsers. I like 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:
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.
Edit
gulp-util is deprecated and should be avoid, so it's recommended to use minimist instead, which gulp-util already used.
So I've changed some lines in my gulpfile to remove 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. It's deprecated in newer versions, so you must use gulp-util for that. 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
Here's a quick recipe I found:
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
gulp scripts --env production
Original Ref (not available anymore): 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
gulpfile.js
// npm install --save-dev gulp gulp-if gulp-uglify minimist
var 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
gulp scripts --env production
There's a very simple way to do on/off flags without parsing the arguments. gulpfile.js is just a file that's executed like any other, so you can do:
var flags = {
production: false
};
gulp.task('production', function () {
flags.production = true;
});
And use something like gulp-if to conditionally execute a step
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.
If you've some strict (ordered!) arguments, then you can get them simply by checking process.argv.
var args = process.argv.slice(2);
if (args[0] === "--env" && args[1] === "production");
Execute it: 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. If nothing was found it spits out 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. (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:
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
I built a plugin to inject parameters from the commandline into the task callback.
gulp.task('mytask', function (production) {
console.log(production); // => true
});
// gulp mytask --production
https://github.com/stoeffel/gulp-param
If someone finds a bug or has a improvement to it, I am happy to merge PRs.
And if you are using typescript (gulpfile.ts) then do this for yargs (building on #Caio Cunha's excellent answer https://stackoverflow.com/a/23038290/1019307 and other comments above):
Install
npm install --save-dev yargs
typings install dt~yargs --global --save
.ts files
Add this to the .ts files:
import { argv } from 'yargs';
...
let debug: boolean = argv.debug;
This has to be done in each .ts file individually (even the tools/tasks/project files that are imported into the gulpfile.ts/js).
Run
gulp build.dev --debug
Or under npm pass the arg through to gulp:
npm run build.dev -- --debug
Pass arguments from the command line
// npm install --save-dev gulp gulp-if gulp-uglify minimist
var 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 in production
.pipe(gulp.dest('dist'));
});
Then run gulp with:
$ gulp scripts --env development
Source
var isProduction = (process.argv.indexOf("production")>-1);
CLI gulp production calls my production task and sets a flag for any conditionals.
It has been some time since this question has been posted, but maybe it will help someone.
I am using GULP CLI 2.0.1 (installed globally) and GULP 4.0.0 (installed locally) here is how you do it without any additional plugin. I think the code is quite self-explanatory.
var cp = require('child_process'),
{ src, dest, series, parallel, watch } = require('gulp');
// == availableTasks: log available tasks to console
function availableTasks(done) {
var command = 'gulp --tasks-simple';
if (process.argv.indexOf('--verbose') > -1) {
command = 'gulp --tasks';
}
cp.exec(command, function(err, stdout, stderr) {
done(console.log('Available tasks are:\n' + stdout));
});
}
availableTasks.displayName = 'tasks';
availableTasks.description = 'Log available tasks to console as plain text list.';
availableTasks.flags = {
'--verbose': 'Display tasks dependency tree instead of plain text list.'
};
exports.availableTasks = availableTasks;
And run from the console:
gulp availableTasks
Then run and see the differences:
gulp availableTasks --verbose
We wanted to pass a different config file for different environments -- one for production, dev and testing. This is the code in the gulp file:
//passing in flag to gulp to set environment
//var env = gutil.env.env;
if (typeof gutil.env.env === 'string') {
process.env.NODE_ENV = gutil.env.env;
}
This is the code in the app.js file:
if(env === 'testing'){
var Config = require('./config.testing.js');
var Api = require('./api/testing.js')(Config.web);
}
else if(env === 'dev'){
Config = require('./config.dev.js');
Api = require('./api/dev.js').Api;
}
else{
Config = require('./config.production.js');
Api = require('./api/production.js')(Config.web);
}
And then to run it gulp --env=testing