How to send in a string into a Gulp task? - javascript

This is step 1 in creating versioned folders for my deployment builds.
How would it be possible to pass in a string into the gulp.task below?
gulp.task('build', function(cb) {
runSequence('html-templates',
'stx-css',
'app-css',
'stx-js',
'app-js',
'build:copy',
'build:remove',
'build:index', cb);
});
I'd like to do something like this: gulp build 1.0.1 which will then pass the string 1.0.1 into the Gulpfile.
gulp.task('build', function(version, cb) {
console.log('version = ', version);
runSequence('html-templates',
'stx-css',
'app-css',
'stx-js',
'app-js',
'build:copy',
'build:remove',
'build:index', cb);
});

This can be accomplished using the env variable!
Great video on the subject:
https://www.youtube.com/watch?v=gRzCAyNrPV8
So I added this to my Gulpfile:
var env = process.env.V; // V={version number}
And then added a version task, which calls a function to print out a string that I pass in before calling my build task:
gulp.task('build', function(cb) {
runSequence('version',
'html-templates',
'stx-css',
'app-css',
'stx-js',
'app-js',
'build:copy',
'build:remove',
'build:index', cb);
});
gulp.task('version', function() {
return printOut(env);
});
function printOut(version) {
console.log('version = ',version);
}

Related

how to setup gulp file for live reload

I am trying to add a couple of gulp tasks. I have a basic HTML site that I want to watch changes for and reload with updated changes. I am trying to use livereload to listen and changed. however when it reloads i get an error that the Port is already in use which makes sense. But I cannot find a solution. First time to use Gulp so any tips on making what I have done better is welcome
var gulp = require('gulp');
var livereload = require('gulp-livereload');
var rev = require('gulp-rev');
var clean = require('gulp-rimraf');
var runSequence = require('run-sequence').use(gulp);
var connect = require('gulp-connect');
gulp.task('build', function () {
// by default, gulp would pick `assets/css` as the base,
// so we need to set it explicitly:
return gulp.src(['assets/css/*.css','assets/css/**/*.css', 'assets/js/*.js', 'assets/js/**/*.js', 'assets/js/**/**/*.js', 'assets/img/**/*.jpg', 'assets/img/**/*.png'], { base: 'assets' })
.pipe(gulp.dest('build/assets')) // copy original assets to build dir
.pipe(rev())
.pipe(gulp.dest('build/assets')) // write rev'd assets to build dir
.pipe(rev.manifest())
.pipe(gulp.dest('build/assets')); // write manifest to build dir
});
gulp.task('copy', function () {
gulp.src('index.html')
.pipe(gulp.dest('build'));
gulp.src('assets/fonts/*.*')
.pipe(gulp.dest('build/assets/fonts'));
gulp.src('assets/fonts/revicons/*.*')
.pipe(gulp.dest('build/assets/fonts/revicons'));
});
gulp.task('clean', [], function() {
return gulp.src("build/*", { read: false }).pipe(clean());
});
gulp.task('watch', function () {
livereload.listen(35729, function(err) {
if(err) return console.log(err);
})
gulp.watch(['index.html', 'assets/css/*.css','assets/css/**/*.css', 'assets/js/*.js', 'assets/js/**/*.js', 'assets/js/**/**/*.js', 'assets/img/**/*.jpg', 'assets/img/**/*.png'], [], function (e) {
livereload.changed(e.path, 35729)
});
});
gulp.task('connect', function() {
connect.server({
host: '0.0.0.0',
root: 'build',
port: 8000,
livereload: true
});
});
gulp.task('default', function() {
runSequence(
'dist',
['connect', 'watch']
);
});
gulp.task('dist', ['clean'], function () {
gulp.start('build');
gulp.start('copy');
});
You may want to check on your host if any process has been running on port - 35729. You can kill that process and try to rerun this application. Find and kill process
or
you can try with different port number than 35729 in your code.
Hope this would help.

Gulp.watch tasks not called (gulp 4.0.0)

I have just migrated an old project from gulp 3 to gulp 4.0.0. I'm having trouble making gulp.watch tasks run within my watch function. I'm running on Windows.
The watch function is as follows:
function watch(done) {
gulp.watch(LAYOUTSFILES, copytosomelocation);
gulp.watch(MODULEFILES, copymodulestosomelocation);
gulp.watch(DLLFILES, gacdeploy);
gulp.watch("./Styles/**/*.less", cssless);
console.log("watching");
done();
}
Locations are formatted as follows (worked in gulp 3, so locations are at least correct):
let LAYOUTSFILES = [
"./Folder/Project/**/*.*"
];
This is the first task being called:
function copytosomelocation() {
console.log("In copy");
return gulp.src(LAYOUTSFILES)
.pipe(fileCache.filter())
.pipe(gulp.dest(OUTLAYOUTS));
}
At the end of the gulpfile, I have exports.watch = watch;.
When I run, I get the following output:
[18:43:59] Using gulpfile
D:\git\repo\folder\someproject\gulpfile.js
[18:43:59] Starting 'watch'...
watching
[18:43:59] Finished 'watch' after 17 ms
That is to say
- No files are copied
- No output is logged to the console from function copytosomelocation.
What am I missing?
I had neglected to take the necessary task dependency changes with me to the new structure.
The original watch function was structured as follows:
gulp.task("watch", ["webpack-watch"], () => { ... });
which described a dependency on the following:
gulp.task('webpack-watch', (done) => {
runWebpack(["-d"], true, done);
});
function runWebpack(params, watch, done) {
params = params || [];
params.push("--color");
if (watch) {
params.push("-w");
}
if (watch) {
spawnCommand("webpack", params);
done(); //return immidiately when watching
} else {
spawnCommand("webpack", params, done);
}
}
Without this functionality gulp was watching a directory which would only be updated when webpack-watch had run. I solved this by updating the watch export as follows:
exports.watch = gulp.series('webpack-watch', watch);

Convert gulp watch in gulp#3.9.1 to gulp#4

We are switching from gulp#3.9.1 to gulp#4 and are having trouble switching over. When we run gulp watch, we are getting the following errors and trying to figure out how to resolve it.
What is the proper way to convert the gulp watch task to work with gulp#4?
Error message
AssertionError [ERR_ASSERTION]: Task never defined: minify-css
Command: gulp watch
This should run minify-js then minify-css in order
minify-js should run after clean-scripts has completed successfully
minify-css should run after clean-css has completed successfully
Current tasks.
var gulp = require('gulp'),
cssmin = require('gulp-clean-css'),
clean = require('gulp-clean'),
uglify = require('gulp-uglify');
var src = {
js: 'js/some-dir/**/*.js',
css: 'css/some-dir/**/*.css'
};
var dest = {
js: 'js/dest/some-dir/**/*.js',
css: 'css/dest/some-dir/**/*.css'
};
gulp.task('clean-css', function() {
return gulp.src(dest.css)
.pipe(clean({read:false, force: true});
});
gulp.task('minify-css', ['clean-css'], function() {
gulp.src(src.css)
.pipe(cssmin())
.pipe(gulp.dest(dest.css));
});
gulp.task('clean-scripts', function() {
return gulp.src(dest.js)
.pipe(clean({read:false, force: true});
});
gulp.task('minify-js', ['clean-scripts'], function() {
gulp.src(src.js)
.pipe(uglify())
.pipe(gulp.dest(dest.js));
});
gulp.task('watch', ['minify-js', 'minify-css'], function() {
gulp.watch(src.js, ['minify-js']);
gulp.watch(src.css, ['minify-css']);
});
We tried doing this, but it resulted in the error message
gulp.task('watch', gulp.series('minify-js', 'minify-css', function() {
gulp.watch(src.js, ['minify-js']);
gulp.watch(src.css, ['minify-css']);
}));
gulp.task('minify-css', gulp.series('clean-css', function() {
return gulp.src(src.css)
.pipe(cssmin())
.pipe(gulp.dest(dest.css));
}));
gulp.task('minify-js', gulp.series('clean-scripts', function() {
return gulp.src(src.js)
.pipe(uglify())
.pipe(gulp.dest(dest.js));
}));
gulp.task('watch', gulp.series('minify-js', 'minify-css', function() {
gulp.watch(src.js, gulp.series('minify-js'));
gulp.watch(src.css, gulp.series('minify-css'));
}));
As #Abdaylan suggested, I also advocate switching to functions. Nevertheless, so you can see where your code was wrong, I have fixed it here. Gulp 4 does not use this syntax:
gulp.task('someTask', ['task1', 'task2'], function () {}); // gulp 3
Gulp 4:
gulp.task('someTask', gulp.series('task1', 'task2', function () {})); // gulp 4 with string tasks
or gulp.parallel. So you can use your gulp.task syntax (rather than named functions) if you modify them to use the signatures that gulp 4 supports as I did in your modified code at the top of this answer.
Gulp 4 with named functions:
gulp.task(someTask, gulp.series(task1, task2, function () {})); // gulp 4 with named functions
So with named functions, the tasks are not referred to as strings.
See also task never defined for other potential problems when migrating from gulp3 to gulp4 with the same error message.
I would recommend converting your minify-js, minify-css, clean-scripts and clean-css tasks to functions:
var dest = {
js: 'js/dest/some-dir/**/*.js',
css: 'css/dest/some-dir/**/*.css'
};
function cleanCss() {
return gulp.src(dest.css)
.pipe(clean({read:false, force: true});
});
function minifyCss() {
return gulp.src(src.css)
.pipe(cssmin())
.pipe(gulp.dest(dest.css));
});
function cleanScripts() {
return gulp.src(dest.js)
.pipe(clean({read:false, force: true});
});
function minifyJs() {
return gulp.src(src.js)
.pipe(uglify())
.pipe(gulp.dest(dest.js));
});
var minifyJsAndClean = gulp.series(minifyJs, cleanScripts);
var minifyCssAndClean = gulp.series(minifyCss, cleanCss);
var watchers = function (done) {
gulp.watch(src.js, minifyJs);
gulp.watch(src.css, minifyCss);
done();
}
gulp.task('watch', gulp.series(minifyJsAndClean, minifyCssAndClean, watchers));
I just ran into this a couple days ago myself. What worked for me was to run each task in its own gulp.watch() with the gulp.series() on the watch task call instead of the watch task itself. For example:
gulp.task('watch', function() {
gulp.watch(src.js, gulp.series('minify-js'));
gulp.watch(src.css, gulp.series('minify-css'));
});

Gulp 4 - watch not watching changes

Today I migrated to Gulp 4, but I'm not able to get my watch function to work.
// Watch
gulp.task('watch', gulp.series('typescript', 'sass', 'browserSync', function(){
gulp.watch('./app/styles/**/*.scss', gulp.series('sass'));
gulp.watch('app/scripts/**/*.ts', gulp.series('typescript'));
gulp.watch('./app/*.html', browserSync.reload);
}));
typescript, sass, browserSync will run but watch does not react to file changes.
I just had the same problem. You don't actually have a reference to the initialized browserSync inside your watch gulp task. Instead of having your browserSync.init function in a separate browserSync gulp task, move it to inside your watch task, and it should work. Hope this helps!
Example:
gulp.task('watch', gulp.series(function (){
browserSync.init({
proxy:"http://localhost:8888",
injectChanges: true,
plugins: ["bs-html-injector?files[]=*.html"]
});
var html = gulp.watch('development/index.html');
html.on('change', function(path, stats) {
console.log('you changed the html');
browserSync.notify("Compiling, please wait!");
browserSync.reload("index.html");
})
var js = gulp.watch('development/**/*.js');
js.on('change', function(path, stats) {
console.log('you changed the js');
browserSync.notify("Compiling, please wait!");
browserSync.reload();
})
var css = gulp.watch('development/**/*.css');
css.on('change', function(path, stats) {
console.log('you changed the css');
browserSync.notify("Injecting CSS!");
browserSync.reload("*.css");
})
}));
Change gulp.watch('app/scripts/**/*.ts', gulp.series('typescript')); to a absolute gulp.watch('./app/scripts/**/*.ts', gulp.series('typescript'));
Also i normally stick this syntax, per task.
var watcher = gulp.watch('js/**/*.js', gulp.parallel('concat', 'uglify'));
watcher.on('change', function(path, stats) {
console.log('File ' + path + ' was changed');
});
I had some issues too, and i found this tutorial of gulp 4, this is my gulpfile to compile scss and watch the Scss files, concat and compile to a main.min.css with autoprefix.
var gulp = require('gulp'),
concat = require('gulp-concat'),
autoprefixer = require('gulp-autoprefixer'),
sass = require('gulp-sass');
//task para o sass
var paths = {
styles: {
src: 'scss/**/*.scss',
dest: 'css'
}
};
function styles() {
return gulp
.src(paths.styles.src, {
sourcemaps: true
})
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(concat('main.min.css'))
.pipe(autoprefixer({
browser: ['last 2 version', '> 5%'],
cascade: false
}))
.pipe(gulp.dest(paths.styles.dest));
}
function watch() {
gulp.watch(paths.styles.src, styles);
}
var build = gulp.parallel(styles, watch);
gulp.task(build);
gulp.task('default', build);
I think that on the gulp v4 you need to use the gulp.parallel. I'm digging to learn more about the new version.

How can I get browserify's "bundle" function to emit an end event?

Say I have some relatively generic browserify scaffolding intended to be used with gulp:
var browserSync = require('browser-sync').create();
var browserify = require('browserify');
var gutil = require('gulp-util');
var exorcist = require('exorcist');
var bundler = browserify('app.jsx', {
debug: false,
extensions: ['.jsx'],
cache: {},
packageCache: {}
});
function bundle() {
return bundler.bundle()
.on('error', function(err) {
gutil.log(err.message);
browserSync.notify('Browserify error!');
this.emit('end');
})
.pipe(source('app.js'))
.pipe(transform(function () {
return exorcist('public/js/app.js.map');
}))
.pipe(gulp.dest('public/js'))
.pipe(browserSync.stream({ once: true }))
}
My issue is that gulp 4 needs explicit notification of completion of tasks, which bundle() as above does not provide:
gulp.task('js', function(callback) {
return bundle();
})
Gulp 4 output:
[timestamp] The following tasks did not complete: js
[timestamp] Did you forget to signal async completion?
However, bundle() doesn't emit an 'end' event on its own, so the below makes the same error:
gulp.task('js', function(callback) {
bundle().on('end', callback);
});
How do I get this function to emit an 'end' event after the last .pipe() call, or otherwise get gulp 4 to recognize the task is finished according to the API docs?
The issue you're facing is that of passing callback, and not calling it. If callback is undefined, all you need to do is return a stream.
The following should do the trick:
gulp.task('js', function () { return bundle(); });
As should this:
gulp.task('js', function (cb) { bundle().on('end', cb); });
You either return or invoke the callback, don't mix the two.
I could be wrong here, but I think the general recommendation is to return.
I don't know what the underlying issue is, but removing the exorcist line in the pipe fixes my problem.

Categories