Running existing task with gulp-watch - javascript

I've got some tasks already defined in gulpfile.js and I want to use gulp-watch plugin (to run tasks on new files). My question is, because I couldn't find anything, can I run my existing tasks while running watch (from plugin) function?
var gulp = require('gulp'),
watch = require('gulp-watch'),
...;
gulp.task('lint', function () {
return gulp.src(path.scripts)
.pipe(jshint())
.pipe(jshint.reporter(stylish));
});
gulp.task('watch', function () {
watch({ glob: 'app/**/*.js' }); // Run 'lint' task for those files
});
Because I don't want to include watch() task in every task I have. I would like to have only 1 task - watch, which will combine all "watches".
----- EDIT ----
(as I probably didn't quite get my point):
I need to run task from inside of gulp('watch') task. for example:
like I did it with gulp.watch:
gulp.task('watch', function () {
gulp.watch('files', ['task1', 'task2']);
});
I need to do the same but with gulp-watch plugin, something like (I know it wouldn't work):
var watch = require('gulp-watch');
gulp.task('watch', function () {
watch({ glob: 'files' }, ['task1', 'task2']);
});

I have also run into the problem of wanting to use gulp-watch (not gulp.watch), needing to use the callback form, and having trouble finding a suitable way to run a task in the callback.
My use case was that I wanted to watch all stylus files, but only process the main stylus file that includes all the others. Newer versions of gulp-watch may address this but I'm having problems with 4.3.x so I'm stuck on 4.2.5.
gulp.run is deprecated so I don't want to use that.
gulp.start works well, but is also advised against by the gulp author, contra.
The run-sequence plugin works well and lets you define a run
order, but it is a self-proclaimed hack:
https://www.npmjs.com/package/run-sequence
Contra suggest writing plain old functions and calling
those. This is a new idea to me, but I think the example below captures the idea. https://github.com/gulpjs/gulp/issues/505
Take your pick.
var gulp = require('gulp'),
watch = require('gulp-watch'), // not gulp.watch
runSequence = require('run-sequence');
// plain old js function
var runStylus = function() {
return gulp.src('index.styl')
.pipe(...) // process single file
}
gulp.task('stylus', runStylus);
gulp.task('watch', function() {
// watch many files
watch('*.styl', function() {
runSequence('stylus');
OR
gulp.start('stylus');
OR
runStylus();
});
});
All of these are working for me without warnings, but I'm still unsure about getting the "done" callback from the 4.2.x version of gulp-watch.

You will most likely want to run specific tasks related to the files you are watching -
gulp.task('watch',['lint'], function () {
gulp.watch('app/**/*.js' , ['lint']);
});
You can also use the ['lint'] portion to run any required tasks when watch first gets called, or utilize the tasks to run async with
gulp.task('default', ['lint','watch'])

You can just call one task, that then includes both task
gulp.task('default', ['lint','watch'])
so here you would just call 'gulp'

gulp.task('watch', function() {
watch(files, function() {
gulp.run(['task1', 'task2']);
});
});
work fine, except a warning

Related

gulp prevent duplicated dependent task execution

looking for some help in refactoring my gulp config file.
I have the following two tasks that both depend on a 3rd task.
I'm trying to get the 3rd task to only run once and save the results instead of having that task run twice.
gulp.task('lint', function(done) {
gulp.task('lib', function(done) {
they both depend on gulp.task('default_preferences', gulp.series('default_preferences-pre'))
previously default_preferences was being called for lint & lib
gulp.task('lint', gulp.series('default_preferences') function(done) {
gulp.task('lib', gulp.series('build_number', 'default_preferences') function(done) {
I have tried to create a new task calling 'default_preferences' and parallel on lint and
lib but then the preferences aren't being found.
gulp.task('createDefault', gulp.series('default_preferences', gulp.parallel('lib', 'lint')), function () {})
I feel like I am missing something obvious, thanks for any help provided!
Hello instead of using gulp task you could try approaching the problem this way:
function lint (done){}
function lib (done){}
exports.default= series(default_preferences-pre, parallel(lint,lib));
exports.lint= lint;
exports.lib= lib;
i hope it helps you

Using Gulp to Minify and Auto Update a CSS File

I have a Gulp task that minifies my CSS in one folder and then pipes it to another folder.
const gulp = require("gulp");
const cleanCSS = require("gulp-clean-css");
gulp.task("minify-css", () => {
return (
gulp
.src("./css/**/*.css")
.pipe(cleanCSS())
.pipe(gulp.dest("minified"))
);
});
The command gulp minify-css works perfectly. I don't want to have to continually type that command in the terminal tho.
I want the code below to watch my CSS file and when it changes I want the minify-css task to run and update my minified file but it doesn't work:
gulp.task("default", function(evt) {
gulp.watch("./css/**/*.css", function(evt) {
gulp.task("minify-css");
});
});
Any ideas on why this doesn't work? Thank you in advance!
The problem lies in the area where you are calling gulp.task('minify-css') inside the gulp.watch callback function. That code does not actually invoke the minify-css task, but rather spawns an anonymous task as pointed by you in your logs. Instead gulp.watch should invoke a function which internally performs the minify-css job.
The other issue is probably the syntax changes that happened in gulp-4. They are not many but can be confusing.
I've managed to fix the issue and it works. Here is the updated code for gulpfile.js below:
const gulp = require("gulp");
const cleanCSS = require("gulp-clean-css");
function minifyCSS() {
return (
gulp
.src("./css/*.css")
.pipe(cleanCSS())
.pipe(gulp.dest("minified"))
);
}
gulp.task("minify-css", minifyCSS);
gulp.task("watch", () => {
gulp.watch("./css/*.css", minifyCSS);
});
gulp.task('default', gulp.series('minify-css', 'watch'));
Hope this helps.

I'm using Gulp and failing to produce the final development script for production.

So I'm having a slight problem with producing production ready scripts for my project. I'm using gulp to concatenate and minify my css and js, and while the css is working fine the gulp js function isn't generating my final file. Please refer to my code below:
gulp.task('js', function() {
return gulp.src([source + 'js/app/**/*.js'])
.pipe(concat('development.js'))
.pipe(gulp.dest(source + 'js'))
.pipe(rename({
basename: 'production',
suffix: '-min',
}))
.pipe(uglify())
.pipe(gulp.dest(source + 'js/'))
.pipe(notify({ message: 'Scripts task complete', onLast: true }));
});
If anyone has encountered a similar problem or has any tips it would be much appreciated :)
There is nothing wrong with your gulpfile. I tested it and it works perfectly.
The only thing I can guess is that your source is not set correctly. Did you forget the trailing slash '/' ?
I would suggest 2 things to figure it out. Include node path library to check where source is actually pointing to like this:
var path = require('path');
// in gulp task ...
path.resolve(path.resolve(source + 'js/app'));
Make sure it points where you think it does.
Secondly, you could use gulp-debug to establish that any files are found:
npm install gulp-debug
Then
var debug = require('gulp-debug');
// in gulp task ...
return gulp.src([source + 'js/app/**/*.js'])
.pipe(concat('development.js'))
.pipe(debug())
.pipe(gulp.dest(source + 'js'))
.pipe(debug())
// etc.
Good luck!
Based on additional infomation in the comments I realise you are generating JS files in a separate process ...
gulp is asynchronous by default. What this boils down to is that all functions try to run at the same time - if you want a specific order it must be by design. This is great because it's very fast but can be a headache to work with.
Problem
Here is what's basically happening:
// SOME TASK THAT SHOULD BE RUN FIRST
gulp.task('copy-vendor-files-to-tempfolder', function (done) {
// copy files to vendor folder
done()
})
// SOME TASKS THAT DEPEND ON FIRST TASK
gulp.task('complile-styles', function () { /* independent task */ })
gulp.task('concat-vendor-files', function () { /* concat files in vendor folder. depends on vendor files existing */ })
// GENERAL TASK WHICH STARTS OTHERS
gulp.task('ready', ['copy-vendor-files-to-tempfolder', 'compile-styles', 'concat-vendor-files])
When you try to run:
$ gulp ready
GULP TASK WILL FAIL! Folder is being created at the same time!!
NOWHERE TO COPY FILES!
Solution
There are many solutions but the following module has come in handy for me again and again:
npm install run-sequence
Then in your gulpfile.js:
var runSequence = require('run-sequence')
gulp.task('ready', function (done) {
runSequence(
'create-folders', // do this first,
[
'copy-css-files',
'copy-html-files'
], // do these AFTER but in parallel
done // callback when ready
)
})
This will guarantee the folder exists when you try to run the other functions.
In your specific case, you should make sure the task that concatenates the JS files is run after the task that copies them out of vendor.
Note: I'm leaving other answer because it contains useful help for debugging similar issues.
HTH!

gulp watch doesn't watch

Following is my gulpfile.js. There are a couple of more tasks in it and all are working fine - but the last task, watch doesn't.
I've tried every possible combination of paths and files and what so ever, but still I don't have luck. I've read many answers on this here, but couldn't solve my problem. I tried to run gulp.watch with and without requiring gulp-watch, tried several different approaches on how to set up the task and so on and so on...
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var watch = require('gulp-watch');
gulp.task('application', function() {
return browserify('./public/resources/jsx/application.js')
.transform(babelify, { stage: 0 })
.bundle()
.on('error', function(e){
console.log(e.message);
this.emit('end');
})
.pipe(source('appBundle.js'))
.pipe(gulp.dest('./public/resources/jsx'));
});
gulp.task('watch', function() {
gulp.watch('./public/resources/jsx/project/*.js',['application'])
});
Can someone suggest a solution?
EDIT:
Here's the console output:
michael#michael-desktop:/opt/PhpstormProjects/app_april_2015$ gulp watch
[23:05:03] Using gulpfile /opt/PhpstormProjects/app_april_2015/gulpfile.js
[23:05:03] Starting 'watch'...
[23:05:03] Finished 'watch' after 13 ms
You should return watch:
gulp.task('watch', function() {
return gulp.watch('./public/resources/jsx/project/*.js',['application'])
});
watch is an async method, so the only way Gulp can know that something is happening is if you return a promise, which watch does.
Edit
As #JMM stated, watch doesn't return a Promise. It returns an EventEmitter.

how to output multiple bundles with browserify and gulp

I have browserify bundling up files and it's working great. But what if I need to generate multiple bundles?
I would like to end up with dist/appBundle.js and dist/publicBundle.js
gulp.task("js", function(){
return browserify([
"./js/app.js",
"./js/public.js"
])
.bundle()
.pipe(source("bundle.js"))
.pipe(gulp.dest("./dist"));
});
Obviously this isn't going to work since I am only specifying one output (bundle.js). I can accomplish this by repeating the above statement like so (but it doesn't feel right, because of the repetition):
gulp.task("js", function(){
browserify([
"./js/app.js"
])
.bundle()
.pipe(source("appBundle.js"))
.pipe(gulp.dest("./dist"));
browserify([
"./js/public.js"
])
.bundle()
.pipe(source("publicBundle.js"))
.pipe(gulp.dest("./dist"));
});
Is there a better way to tackle this? Thanks!
I don't have a good environment to test this in right now, but my guess is that it would look something like:
gulp.task("js", function(){
var destDir = "./dist";
return browserify([
"./js/app.js",
"./js/public.js"
])
.bundle()
.pipe(source("appBundle.js"))
.pipe(gulp.dest(destDir))
.pipe(rename("publicBundle.js"))
.pipe(gulp.dest(destDir));
});
EDIT: I just realized I mis-read the question, there should be two separate bundles coming from two separate .js files. In light of that, the best alternative I can think of looks like:
gulp.task("js", function(){
var destDir = "./dist";
var bundleThis = function(srcArray) {
_.each(srcArray, function(source) {
var bundle = browserify(["./js/" + source + ".js"]).bundle();
bundle.pipe(source(source + "Bundle.js"))
.pipe(gulp.dest(destDir));
});
};
bundleThis(["app", "public"]);
});
gulp.task("js", function (done) {
[
"app",
"public",
].forEach(function (entry, i, entries) {
// Count remaining bundling operations to track
// when to call done(). Could alternatively use
// merge-stream and return its output.
entries.remaining = entries.remaining || entries.length;
browserify('./js/' + entry + '.js')
.bundle()
// If you need to use gulp plugins after bundling then you can
// pipe to vinyl-source-stream then gulp.dest() here instead
.pipe(
require('fs').createWriteStream('./dist/' + entry + 'Bundle.js')
.on('finish', function () {
if (! --entries.remaining) done();
})
);
});
});
This is similar to #urban_racoons answer, but with some improvements:
That answer will fail as soon as you want the task to be a dependency of another task in gulp 3, or part of a series in gulp 4. This answer uses a callback to signal task completion.
The JS can be simpler and doesn't require underscore.
This answer is based on the premise of having a known list of entry files for each bundle, as opposed to, say, needing to glob a list of entry files.
Multiple bundles with shared dependencies
I recently added support for multiple bundles with shared dependencies to https://github.com/greypants/gulp-starter
Here's the array of browserify config objects I pass to my browserify task. At the end of that task, I iterate over each config, browserifying all the things.
config.bundleConfigs.forEach(browserifyThis);
browserifyThis takes a bundleConfig object, and runs browserify (with watchify if dev mode).
This is the bit that sorts out shared dependencies:
// Sort out shared dependencies.
// b.require exposes modules externally
if(bundleConfig.require) b.require(bundleConfig.require)
// b.external excludes modules from the bundle, and expects
// they'll be available externally
if(bundleConfig.external) b.external(bundleConfig.external)
This browserify task also properly reports when all bundles are finished (the above example isn't returning streams or firing the task's callback), and uses watchify when in devMode for super fast recompiles.
Brian FitzGerald's last comment is spot on. Remember that it's just JavaScript!

Categories

Resources