Update the gulp watch function to use gulp@4

We are currently in the process of transitioning from

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb9c8e978bbbc8d5c2d5ca">[email protected]</a>
to gulp@4, and encountering difficulties during the switch. Upon running gulp watch, we encountered the errors below and are seeking a solution.

How can we successfully convert the gulp watch task for compatibility with gulp@4?

Error message

AssertionError [ERR_ASSERTION]: Task never defined: minify-css

Command: gulp watch

  • This should execute minify-js followed by minify-css sequentially
  • minify-js should be triggered only after successful completion of clean-scripts
  • minify-css should run after clean-css has successfully executed

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']);
});

Although an attempt was made using this code snippet, it resulted in an error message:

gulp.task('watch', gulp.series('minify-js', 'minify-css', function() {
  gulp.watch(src.js, ['minify-js']);
  gulp.watch(src.css, ['minify-css']);
}));

Answer №1

gulp.task('compress-styles', gulp.series('clear-css', function() {
  return gulp.src(source.styles)
    .pipe(cssmin())
    .pipe(gulp.dest(destination.styles));
}));

gulp.task('compress-scripts', gulp.series('clear-js', function() {
   return gulp.src(source.scripts)
       .pipe(uglify())
       .pipe(gulp.dest(destination.scripts));
}));

gulp.task('monitor', gulp.series('compress-scripts', 'compress-styles', function() {
  gulp.watch(source.scripts, gulp.series('compress-scripts'));
  gulp.watch(source.styles, gulp.series('compress-styles'));
}));

In agreement with @Abdaylan, I also recommend moving to functions for more clarity. However, here are the corrections made to your code. It's important to note that Gulp 4 does not utilize the syntax shown below:

gulp.task('someTask', ['task1', 'task2'], function () {});  // gulp 3

Gulp 4:

gulp.task('someTask', gulp.series('task1', 'task2', function () {}));  // gulp 4 with string tasks

or by using gulp.parallel. By adapting your existing syntax to the supported signatures of Gulp 4 as outlined in the modified code above, you can continue utilizing the gulp.task approach.

Gulp 4 with named functions:

gulp.task(someTask, gulp.series(task1, task2, function () {}));  // gulp 4 with named functions

With named functions, the tasks are not referenced as strings like before.

For additional reference on migrating from gulp3 to gulp4 and potential errors that may arise, please check out task never defined.

Answer №2

I suggest transforming your minify-js, minify-css, clean-scripts, and clean-css tasks into 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));

Answer №3

A few days back, I faced a similar issue and found a solution that worked well for me. Instead of running all tasks within the same gulp.watch(), I ran each task separately using gulp.series() on the watch task call. Here's an example:

gulp.task('watch', function() {
  gulp.watch(src.js, gulp.series('minify-js'));
  gulp.watch(src.css, gulp.series('minify-css'));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arrange an array of objects based on boolean values first, followed by numerical values in JavaScript

I am facing a challenge where I have an array of objects that need to be sorted based on two rules, following a specific order: Firstly, objects with the "departeYet" property set to true should come first. Secondly, the objects must then be sorted numeri ...

Error message due to an undefined function in Angular datatables Fixed Columns

I recently implemented angular datatables with fixed column in my application. Here is the HTML code I used for the view: <div class="row" ng-controller="PerformanceCtrl"> <table id="example" datatable="" class="stripe row-border or ...

Steps for connecting data to a react table

This is my first time working with React and I want to display the following data (id, name, status, and quantity): interface Goods { id: number; name: string; status: string; quantity?: number; } export const getGoods = (): Promise<Goods[]> ...

JSON.stringify not behaving as anticipated

I am working on the code below; var data = []; data['id'] = 105; data['authenticated'] = true; console.log(data); var jsonData = JSON.stringify(data); console.log(jsonData); The initial console.log is displaying; [id: 105, authenti ...

Creating a Timeless Banner with the Magic of `background:url()`

I have a banner placed within a div tag that displays my banner image. I am trying to create a fading effect when transitioning to the next image, but I am struggling to achieve this. I attempted to use jQuery fadeIn(), however, it did not work as expected ...

Model of Objects within a Document

Here's a puzzling question for you: why does console.log(document.body) and console.log(document.head) work perfectly fine, but console.log(document.script) or console.log(document.html) don't seem to do anything? It's strange because all of ...

Is it possible to simultaneously toggle buttons and submit a form?

I am currently working on a functionality that involves toggling the display of two buttons and submitting a form. Code toggleButtons() { var btn1 = document.getElementById("start"); var btn2 = document.getElementById("pause"); if (btn1.style. ...

Interactive horizontal slideshow for hyperlinks - bootstrap framework and model-view-controller architecture

I am currently working on an MVC project that utilizes Bootstrap. My requirement is to have a horizontal menu of links that can slide left and right using arrows (similar to a carousel, but for links instead of images). To be more specific, the menu need ...

Is Express capable of serving static files from a hidden folder with dot file?

I have set up my app to serve a static folder in the following way: app.use('/static', serveStatic(__dirname + '/view/my/static/folder')); Now, I am wondering how to configure the server to serve a hidden folder. For example, if I hav ...

Every time I try to create a new React app, I consistently run into the same error

I keep encountering this error every time I try to create a React app using create-react-app. ...

Using conditionals in CMD commands within a Docker environment

My goal is to execute CMD ["npm", "run", "dev"] if a development script exists in package.json; otherwise, I want to run CMD ["npm", "start"]. Is there a standard Docker approach to achieve this? I was thinking of having a CMD as a bash script that verifi ...

Breaking down objects or arrays to extract specific values in React components

Some articles recommend using ES6 destructuring for React props & state as a best practice. For example: const { showModal, hideModal } = this.props; While I understand the benefits of cleaner code, I recently discussed with another developer who suggest ...

Is there a way to modify the style within a TS-File?

I've created a service to define different colors and now I want to set separate backgrounds for my columns. However, using the <th> tag doesn't work because both columns immediately get the same color. Here's my code: color-variatio ...

Is jQuery.each() failing to function properly in Firefox and Internet Explorer?

Having trouble with the $.each function behaving differently across browsers. I have lists with background images, and I want the parent div to fade in once these images finish loading. My code seems correct as there are no JavaScript errors in the conso ...

How to utilize jQuery to replace the first occurrence of a specific

Suppose I have an array structured like this: var acronyms = {<br> 'NAS': 'Nunc ac sagittis',<br> 'MTCP': 'Morbi tempor congue porta'<br> }; My goal is to locate the first occurrence ...

converting nested object structures in typescript

I'm trying to flatten a nested object in my Loopback and Typescript controller Here's the structure of my model : export class SampleModel { id: number; code: number; guide?: string; gradeData?: string; } Take a look at this example obj ...

How can I use PHP to transform a JSON object containing xy coordinates into an image?

What is the best way to convert a JSON object containing xy coordinates into an image (PNG or JPG) using PHP or JavaScript? ...

Iterating over an array of objects and executing asynchronous operations

I am currently working with NextJS and managing an array of assets (images) within my state. The task at hand is to post these images to the API. To accomplish this, I have a specific object that handles the posting process using the following syntax: let ...

Upcoming topics - The Challenge of Staying Hydrated at Basecamp One

I have implemented a themes package for dark mode and light mode in my project. Despite doing the installation correctly as per the repository instructions, I am encountering an issue. My expected behavior for the project is: The webpage should initially ...

Enhance your web form with an auto-suggest textbox that allows for multiple selections,

Looking for assistance in implementing an auto complete text box with the ability to select multiple options using Dojo. Any experts out there who can offer their guidance? ...