elixir.queueTask is undefined - gulp

I am fairly new to Laravel 5.2 and Elixir/gulp but I have an issue with queueTask being undefined when I run gulp from the command line.
What I want to do is to extend elixir to delete some files (according to all the documentation I can find, that's what I need to do), so I have this:
var gulp = require('gulp');
var elixir = require("laravel-elixir");
var del = require('del');
elixir.extend("remove", function(path) {
gulp.task("removeFiles", function() {
return del(path);
});
return this.queueTask("removeFiles");
});
and then in my mix I have:
.remove([
"path/to/file1/filename1",
"path/to/file2/filename2"
])
When I run gulp in the command line, I get:
return this.queueTask("removeFiles");
^
TypeError: undefined is not a function
can anyone throw some light on what I am doing wrong please?

API has changed again since Elixir v3.0.0. So for v4.0.0 you must do this:
var elixir = require('laravel-elixir');
var del = require('del');
var Task = elixir.Task;
elixir.extend('remove', function (path) {
new Task('remove', function () {
return del(path);
});
});
And then you can call it within your pipeline like this:
mix.remove([
"path/to/file1/filename1",
"path/to/file2/filename2"
]);
The difference seems to be calling elixir.extend as opposed to elixir.Task.extend. And then returning a new elixir.Task.

API was changed in Elixir v3.0.0.
You no longer need to call Gulp.task(). Elixir will handle that, instead you have to create a new Task.
var Elixir = require('laravel-elixir');
var del = require('del');
Elixir.Task.extend('remove', function (path) {
new Task('remove', function () {
return del(path);
});
});

Related

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

I have the following gulpfile.js, which I'm executing via the command line gulp message:
var gulp = require('gulp');
gulp.task('message', function() {
console.log("HTTP Server Started");
});
I'm getting the following error message:
[14:14:41] Using gulpfile ~\Documents\node\first\gulpfile.js
[14:14:41] Starting 'message'...
HTTP Server Started
[14:14:41] The following tasks did not complete: message
[14:14:41] Did you forget to signal async completion?
I'm using gulp 4 on a Windows 10 system. Here is the output from gulp --version:
[14:15:15] CLI version 0.4.0
[14:15:15] Local version 4.0.0-alpha.2
Since your task might contain asynchronous code you have to signal gulp when your task has finished executing (= "async completion").
In Gulp 3.x you could get away without doing this. If you didn't explicitly signal async completion gulp would just assume that your task is synchronous and that it is finished as soon as your task function returns. Gulp 4.x is stricter in this regard. You have to explicitly signal task completion.
You can do that in six ways:
1. Return a Stream
This is not really an option if you're only trying to print something, but it's probably the most frequently used async completion mechanism since you're usually working with gulp streams. Here's a (rather contrived) example demonstrating it for your use case:
var print = require('gulp-print');
gulp.task('message', function() {
return gulp.src('package.json')
.pipe(print(function() { return 'HTTP Server Started'; }));
});
The important part here is the return statement. If you don't return the stream, gulp can't determine when the stream has finished.
2. Return a Promise
This is a much more fitting mechanism for your use case. Note that most of the time you won't have to create the Promise object yourself, it will usually be provided by a package (e.g. the frequently used del package returns a Promise).
gulp.task('message', function() {
return new Promise(function(resolve, reject) {
console.log("HTTP Server Started");
resolve();
});
});
Using async/await syntax this can be simplified even further. All functions marked async implicitly return a Promise so the following works too (if your node.js version supports it):
gulp.task('message', async function() {
console.log("HTTP Server Started");
});
3. Call the callback function
This is probably the easiest way for your use case: gulp automatically passes a callback function to your task as its first argument. Just call that function when you're done:
gulp.task('message', function(done) {
console.log("HTTP Server Started");
done();
});
4. Return a child process
This is mostly useful if you have to invoke a command line tool directly because there's no node.js wrapper available. It works for your use case but obviously I wouldn't recommend it (especially since it's not very portable):
var spawn = require('child_process').spawn;
gulp.task('message', function() {
return spawn('echo', ['HTTP', 'Server', 'Started'], { stdio: 'inherit' });
});
5. Return a RxJS Observable.
I've never used this mechanism, but if you're using RxJS it might be useful. It's kind of overkill if you just want to print something:
var of = require('rxjs').of;
gulp.task('message', function() {
var o = of('HTTP Server Started');
o.subscribe(function(msg) { console.log(msg); });
return o;
});
6. Return an EventEmitter
Like the previous one I'm including this for completeness sake, but it's not really something you're going to use unless you're already using an EventEmitter for some reason.
gulp.task('message3', function() {
var e = new EventEmitter();
e.on('msg', function(msg) { console.log(msg); });
setTimeout(() => { e.emit('msg', 'HTTP Server Started'); e.emit('finish'); });
return e;
});
An issue with Gulp 4.
For solving this problem try to change your current code:
gulp.task('simpleTaskName', function() {
// code...
});
for example into this:
gulp.task('simpleTaskName', async function() {
// code...
});
or into this:
gulp.task('simpleTaskName', done => {
// code...
done();
});
You need to do one thing:
Add async before function.
const gulp = require('gulp');
gulp.task('message', async function() {
console.log("Gulp is running...");
});
THIS WORKED!
The latest update on Feb 18, 2021, I found the problem after using the elder solution below, then I have fixed it by using the following instead for the next gulp version.
File: Package.json
...,
"devDependencies": {
"del": "^6.0.0",
"gulp": "^4.0.2",
},
...
File: gulpfile.js Example
const {task} = require('gulp');
const del = require('del');
async function clean() {
console.log('processing ... clean');
return del([__dirname + '/dist']);
}
task(clean)
...
Elder Version
gulp.task('script', done => {
// ... code gulp.src( ... )
done();
});
gulp.task('css', done => {
// ... code gulp.src( ... )
done();
});
gulp.task('default', gulp.parallel(
'script',
'css'
)
);
I was getting this same error trying to run a very simple SASS/CSS build.
My solution (which may solve this same or similar errors) was simply to add done as a parameter in the default task function, and to call it at the end of the default task:
// Sass configuration
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
gulp.src('*.scss')
.pipe(sass())
.pipe(gulp.dest(function (f) {
return f.base;
}))
});
gulp.task('clean', function() {
})
gulp.task('watch', function() {
gulp.watch('*.scss', ['sass']);
})
gulp.task('default', function(done) { // <--- Insert `done` as a parameter here...
gulp.series('clean','sass', 'watch')
done(); // <--- ...and call it here.
})
Hope this helps!
This is an issue when migrating from gulp version 3 to 4, Simply you can add a parameter done to the call back function , see example,
const gulp = require("gulp")
gulp.task("message", function(done) {
console.log("Gulp is running...")
done()
});
I cannot claim to be very knowledgeable on this but I had the same problem and have resolved it.
There is a 7th way to resolve this, by using an async function.
Write your function but add the prefix async.
By doing this Gulp wraps the function in a promise, and the task will run without errors.
Example:
async function() {
// do something
};
Resources:
Last section on the Gulp page Async Completion: Using async/await.
Mozilla async functions docs.
You need to do two things:
Add async before function.
Start your function with return.
var gulp = require('gulp');
gulp.task('message', async function() {
return console.log("HTTP Server Started");
});
Workaround: We need to call the callback functions (Task and Anonymous):
function electronTask(callbackA)
{
return gulp.series(myFirstTask, mySeccondTask, (callbackB) =>
{
callbackA();
callbackB();
})();
}
Basically v3.X was simpler but v4.x is strict in these means of synchronous & asynchronous tasks.
The async/await is pretty simple & helpful way to understand the workflow & issue.
Use this simple approach
const gulp = require('gulp')
gulp.task('message',async function(){
return console.log('Gulp is running...')
})
Here you go: No synchronous tasks.
No synchronous tasks
Synchronous tasks are no longer supported. They often led to subtle mistakes that were hard to debug, like forgetting to return your streams from a task.
When you see the Did you forget to signal async completion? warning, none of the techniques mentioned above were used. You'll need to use the error-first callback or return a stream, promise, event emitter, child process, or observable to resolve the issue.
Using async/await
When not using any of the previous options, you can define your task as an async function, which wraps your task in a promise. This allows you to work with promises synchronously using await and use other synchronous code.
const fs = require('fs');
async function asyncAwaitTask() {
const { version } = fs.readFileSync('package.json');
console.log(version);
await Promise.resolve('some result');
}
exports.default = asyncAwaitTask;
My solution: put everything with async and await gulp.
async function min_css() {
return await gulp
.src(cssFiles, { base: "." })
.pipe(concat(cssOutput))
.pipe(cssmin())
.pipe(gulp.dest("."));
}
async function min_js() {
return await gulp
.src(jsFiles, { base: "." })
.pipe(concat(jsOutput))
.pipe(uglify())
.pipe(gulp.dest("."));
}
const min = async () => await gulp.series(min_css, min_js);
exports.min = min;
Solution is simple, but I outline the changes I made, the error I was getting, my gulpfile before and after, and the package versions--therefore making it appear very long.
I solved this by following the directions of multiple previous answers, in addition to following the error outputted when I would save my .scss file.
In short:
I changed how gulp-sass was imported—see (A)
I changed all functions to ASYNC functions—see (B)
(A) Changes made to gulp-sass import:
Before: var sass = require('gulp-sass)
After: var sass = require('gulp-sass')(require('sass'));
(B) Simply convert functions to ASYNC—
What my gulpfile looked like before:
'use strict';
// dependencies
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifyCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var changed = require('gulp-changed');
var SCSS_SRC = './src/Assets/scss/**/*.scss';
var SCSS_DEST = './src/Assets/css';
function compile_scss() {
return gulp.src(SCSS_SRC)
.pipe(sass().on('error', sass.logError))
.pipe(minifyCSS())
.pipe(rename({ suffix: '.min' }))
.pipe(changed(SCSS_DEST))
.pipe(gulp.dest(SCSS_DEST));
}
function watch_scss() {
gulp.watch(SCSS_SRC, compile_scss);
}
gulp.task('default', watch_scss); //Run tasks
exports.compile_scss = compile_scss;
exports.watch_scss = watch_scss;
What my gulpfile looked like after:
'use strict';
// dependencies
var gulp = require('gulp');
//var sass = require('gulp-sass');
var sass = require('gulp-sass')(require('sass'));
var minifyCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var changed = require('gulp-changed');
var SCSS_SRC = './src/Assets/scss/**/*.scss';
var SCSS_DEST = './src/Assets/css';
async function compile_scss() {
return gulp.src(SCSS_SRC)
.pipe(sass().on('error', sass.logError))
.pipe(minifyCSS())
.pipe(rename({ suffix: '.min' }))
.pipe(changed(SCSS_DEST))
.pipe(gulp.dest(SCSS_DEST));
}
async function watch_scss() {
gulp.watch(SCSS_SRC, compile_scss);
}
gulp.task('default', watch_scss); // Run tasks
exports.compile_scss = compile_scss;
exports.watch_scss = watch_scss;
Package Versions:
"gulp": "^4.0.2",
"gulp-changed": "^4.0.3",
"gulp-rename": "^2.0.0",
"gulp-uglify": "^3.0.2",
"gulp-clean-css": "^4.3.0",
"gulp-sass": "^5.0.0",
"sass": "^1.38.0"
Error I was getting:
Error in plugin "gulp-sass"
Message:
gulp-sass 5 does not have a default Sass compiler; please set one yourself.
Both the `sass` and `node-sass` packages are permitted.
For example, in your gulpfile:
var sass = require('gulp-sass')(require('sass'));
[14:00:37] The following tasks did not complete: default, compile_scss
[14:00:37] Did you forget to signal async completion?
I got that solved, It's Pretty simple just add the below code snippet.
var gulp = require('gulp');
gulp.task('message', async function() {
console.log("HTTP Server Started");
});
I was struggling with this recently, and found the right way to create a default task that runs sass then sass:watch was:
gulp.task('default', gulp.series('sass', 'sass:watch'));
In gulp version 4 and over, it is required that all gulp tasks tell Gulp where the task will end. We do this by calling a function that is passed as the first argument in our task function
var gulp = require('gulp');
gulp.task('first_task', function(callback) {
console.log('My First Task');
callback();
})
Add done as a parameter in default function. That will do.
For those who are trying to use gulp for swagger local deployment, following code will help
var gulp = require("gulp");
var yaml = require("js-yaml");
var path = require("path");
var fs = require("fs");
//Converts yaml to json
gulp.task("swagger", done => {
var doc = yaml.safeLoad(fs.readFileSync(path.join(__dirname,"api/swagger/swagger.yaml")));
fs.writeFileSync(
path.join(__dirname,"../yourjsonfile.json"),
JSON.stringify(doc, null, " ")
);
done();
});
//Watches for changes
gulp.task('watch', function() {
gulp.watch('api/swagger/swagger.yaml', gulp.series('swagger'));
});
For me the issue was different: Angular-cli was not installed (I installed a new Node version using NVM and simply forgot to reinstall angular cli)
You can check running "ng version".
If you don't have it just run "npm install -g #angular/cli"
I know the problem was presented 6 years ago but probabily you missed return in your function.
I fixed this issue this morning with eslint, that gave me the same message after running "gulp lint" in my working directory.
Example:
function runLinter(callback)
{
return src(['**/*.js', '!node_modules/**'])
.pipe(eslint())
.on('end', ()=>
{
callback();
});
}
exports.lint = runLinter;
So I got the same error with Gulp 4, but the solution was different. I had the error:
"Did you forget to signal async completion?"
but before the error it also says:
"gulp-sass no longer has a default Sass compiler; please set one yourself"
I completely missed that part at first.
So I had this in the gulfile.js:
const sass = require('gulp-sass')
This should be changed to:
const sass = require('gulp-sass')(require('sass'));
Now it works.

How do I get Object.assign to work with 6to5 polyfill?

I am trying to use Object.assign from ES6, but it is always undefined. Here is the file where I am using it:
var Dispatcher = require('./dispatcher.js');
export default Object.assign(Dispatcher.prototype, {
handleViewAction(action) {
this.dispatch({
source: 'VIEW_ACTION',
action: action
});
}
});
And here is the gulp task I am using to transpile the code:
var browserify = require('browserify');
var reactify = require('reactify');
var source = require('vinyl-source-stream')
var to5 = require('6to5ify');
module.exports = function(gulp, config) {
gulp.task('browserify', function() {
browserify(config.app.entry, {debug: true})
.add(require.resolve('6to5/polyfill'))
.transform(to5)
.transform(reactify)
.bundle()
.pipe(source(config.app.bundleName))
.pipe(gulp.dest(config.app.bundle));
});
};
My Object is valid, but assign is undefined. What am I doing wrong?
Babeljs (formerly 6to5) does not transform or polyfill Object.assign.
You will need to use another polyfill library. 2 popular libraries are core-js or object-assign.
With core-js you would do it like this:
require('core-js');
Object.assign({}, {a:1});
or
var core = require('core-js/library');
var result = core.Object.assign({}, {a:1});
With object-assign:
var _assign = require('object-assign');
var result = _assign({}, {a:1});
But there are of course a lot of other libraries which do the same.

Sequencing tasks with gulp

I'm a bit stumped with gulp. Based on the docs, in order to get sequential execution, I should be returning the stream from my tasks, so i tried to do the below for my gulpfile. But as best I can tell, there's a race condition. Half the time I get ENOENT, lstat errors, the other half it succeeds, but my deployDir has weird folder names and missing files all over.. Am I missing something? Is there a trick to this?
var gulp = require('gulp'),
filter = require('gulp-filter'),
mainBowerFiles = require('main-bower-files'),
del = require('del'),
inject = require("gulp-inject"),
uglify = require('gulp-uglifyjs');
var config = {
bowerDir: 'src/main/html/bower_components',
cssDir: 'src/main/html/css/lib',
fontsDir: 'src/main/html/fonts/lib',
imgDir: 'src/main/html/img/lib',
jsDir: 'src/main/html/js/lib',
deployDir: 'src/main/resources/html'
};
gulp.task('default', ['clean', 'bowerdeps', 'dev']);
gulp.task('clean', function() {
return del([
config.cssDir,
config.fontsDir,
config.jsDir,
config.deployDir
]);
});
gulp.task('dev', function() {
return gulp
.src(['src/main/html/**', '!src/main/html/{bower_components,bower_components/**}'])
.pipe(gulp.dest(config.deployDir));
});
gulp.task('bowerdeps', function() {
var mainFiles = mainBowerFiles();
if(!mainFiles.length) return; // No files found
var jsFilter = filterByRegex('.js$');
var cssFilter = filterByRegex('.css$');
var fontFilter = filterByRegex('.eot$|.svg$|.ttf$|.woff$');
return gulp
.src(mainFiles)
.pipe(jsFilter)
.pipe(gulp.dest(config.jsDir))
.pipe(jsFilter.restore())
.pipe(cssFilter)
.pipe(gulp.dest(config.cssDir))
.pipe(cssFilter.restore())
.pipe(fontFilter)
.pipe(gulp.dest(config.fontsDir));
});
// Utility Functions
var filterByRegex = function(regex){
return filter(function(file){
return file.path.match(new RegExp(regex));
});
};
Dependencies run always parallel: ['clean', 'bowerdeps', 'dev'].
https://github.com/gulpjs/gulp/blob/master/docs/recipes/running-tasks-in-series.md
You can use run-sequence for sequencing tasks.
Other thing: del doesn't return a stream. Use callback instead:
gulp.task('clean', function(cb) {
del([
config.cssDir,
config.fontsDir,
config.jsDir,
config.deployDir
], cb);
});

Running pipeline section multiple times with different arguments for concat step

I'm a fan of the files object format
files: {
'dest/a.js': ['src/aa.js', 'src/aaa.js'], // key: value
'dest/a1.js': ['src/aa1.js', 'src/aaa1.js'],
}
I have a gulp task that concats source files like
gulp.task('cat', function() {
gulp.src( <value-goes-here> )
.
<many pipeline steps>
.
.pipe(concat(<key-goes-here>))
.pipe(gulp.dest('target/')
.
<more pipeline steps to be run on 'dest/a.js' and 'dest/a1.js'>
.
});
Is there a streaming way to extend this task so that I get 1 bundle file for each key-value in files ?
I would like to NOT create one task per key-value pair, as I would like to continue piping more steps even after the last .pipe(gulp.dest('target/');
If I'm approaching this problem in wrong way, is there a better way?
Thank you in advance!
Rob Rich's answer works, Heres working version :
var Q = require('q');
var gulp = require('gulp');
var concat = require('gulp-concat');
var files = {
'a.js': ['src/aa.js', 'src/aaa.js'],
'a1.js': ['src/aa1.js', 'src/aaa1.js'],
};
gulp.task('cat', function() {
var promises = Object.keys(files).map(function (key) {
var deferred = Q.defer();
var val = files[key];
console.log(val);
gulp.src(val)
.pipe(concat(key))
.pipe(gulp.dest('dest/'))
.on('end', function () {
deferred.resolve();
});
return deferred.promise;
});
return Q.all(promises);
});
Try this:
var Q = require('q');
gulp.task('cat', function() {
var promises = Object.keys(files).map(function (key) {
var deferred = Q.defer();
var val = files[key];
gulp.src(val)
.
<many pipeline steps>
.
.pipe(concat(key))
.pipe(gulp.dest('target/')
.
<more pipeline steps to be run on 'dest/a.js' and 'dest/a1.js'>
.
.on('end', function () {
deferred.resolve();
});
return deferred.promise;
});
return Q.all(promises);
});
You can also accomplish a similar scenario by using streams instead of promises by using combined-stream or stream-combiner packages.

Determining if Gulp task called from another task

Is there a way to find out if a task been invoked directly or from another task?
runSequence = require 'run-sequence'
gulp.task 'build', ->
....
gulp.task 'run', ->
runSequence 'build', -> gulp.start('server')
I need an if case in build task that says:
if it was called directly - (gulp build) then do something;
or if it was invoked from run task then do something else
This might be an X/Y problem. What are you actually trying to accomplish?
But to answer the question; I think the only way is to look at the call stack trace and make sure only Gulp touches the task. I wrote a function that finds who orchestrated the task. You can just put the function inline with your gulpfile.js and use it like boolean.
The following code relies on npm parse-stack so make sure to npm install parse-stack
Usage: if(wasGulpTaskCalledDirectly()) { /*...*/ }
function wasGulpTaskCalledDirectly()
{
var parseStack = require("parse-stack");
var stack = parseStack(new Error());
// Find the index in the call stack where the task was started
var stackTaskStartIndex = -1;
for(var i = 0; i < stack.length; i++)
{
if(stack[i].name == 'Gulp.Orchestrator.start')
{
stackTaskStartIndex = i;
break;
}
}
// Once we find where the orchestrator started the task
// Find who called the orchestrator (one level up)
var taskStarterIndex = stackTaskStartIndex+1;
var isValidIndex = taskStarterIndex > 0 && taskStarterIndex < stack.length;
if(isValidIndex && /gulp\.js$/.test((stack[taskStarterIndex].filepath || "")))
{
return true;
}
return false;
}
You can find my full gulpfile.js used for testing below:
// This is a test for this SE question: http://stackoverflow.com/q/25928170/796832
// Figure out how to detect `gulp` vs `gulp build`
// Include gulp
var gulp = require('gulp');
var runSequence = require('run-sequence');
// Add this in from the above code block in the answer
//function wasGulpTaskCalledDirectly()
// ...
gulp.task('build', function() {
//console.log(wasGulpTaskCalledDirectly());
if(wasGulpTaskCalledDirectly())
{
// Do stuff here
}
else
{
// Do other stuff here
}
return gulp.src('./index.html', {base: './'})
.pipe(gulp.dest('./dist'));
});
// This does nothing
gulp.task('start-server', function() {
return gulp.src('./index.html', {base: './'});
});
// Default Task
gulp.task('default', function(callback) {
runSequence('build',
['start-server'],
callback
);
});