AssertionError [ERR_ASSERTION] - gulp

I have gulp file that is having issues with latest update to gulp 4 I am getting assertion errors (AssertionError [ERR_ASSERTION]: Task function must be specified) and it seems (from googling) to have to do with how tasks are defined, but not sure if this is the case here and what needs to change.
Node: node -v
v14.16.0
CLI version: 2.3.0
Local version: 4.0.2
NPM: 6.14.11
Here is the code
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(function() {
return gulpif('*.less', less());
})
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12'
]
})
.pipe(cssNano, {
safe: true
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/styles/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/scripts/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(plumber({errorHandler: onError}))
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(plumber({errorHandler: onError}))
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
//.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin([
imagemin.jpegtran({progressive: true}),
imagemin.gifsicle({interlaced: true}),
imagemin.svgo({plugins: [
{removeUnknownsAndDefaults: false},
{cleanupIDs: false}
]})
]))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
Any help is greatly appreciated.

So there are a few things wrong with your code.
gulp.task('styles', ['wiredep'], function() {
for example should be
gulp.task('styles', gulp.series('wiredep', function() { etc.
gulp.task only takes three arguments. You may have more places in your code like this.
gulp.watch([path.source + 'styles/**/*'], ['styles']); might actually be fine but lets be careful and make it a little more future-proof:
gulp.watch([path.source + 'styles/**/*'], gulp.series('styles'));
Etc. change all of these in your watch task.
With gulp.series and gulp.parallel you no longer need something like runSequence. So replace
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images'],
callback);
});
with
gulp.task('build', gulp.series(
'styles',
'scripts',
gulp.parallel('fonts', 'images')
// callback); // see below
);
Make these changes and you'll see if you need the `callback` in the `build` task - if you get a message about signaling async completion.
-----------
And you may have to move your `wiredep` task before your `styles` task. Since you are using `gulp.task` rather than functions to create your tasks, you cannot refer to a task that hasn't been created yet. That wouldn't be an issue if you used all named functions to create each task.

Related

error: gulp.start is not a function while using gulp version 4

Iam using gulp CLI version: 2.2.1 Local version: 4.0.2
The node version is 12.16.3
MY code of gulpfile.js is
'use strict';
var gulp = require('gulp'),
sass = require('gulp-sass'),
browserSync = require('browser-sync'),
del=require('del'),
imagemin = require('gulp-imagemin'),
uglify = require('gulp-uglify'),
usemin = require('gulp-usemin'),
rev = require('gulp-rev'),
cleanCss = require('gulp-clean-css'),
flatmap = require('gulp-flatmap'),
htmlmin = require('gulp-htmlmin');
gulp.task('sass', function () {
return gulp.src('./css/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
gulp.task('sass:watch', function () {
gulp.watch('./css/*.scss', ['sass']);
});
gulp.task('browser-sync', function () {
var files = [
'./*.html',
'./css/*.css',
'./img/*.{png,jpg,gif}',
'./js/*.js'
];
browserSync.init(files, {
server: {
baseDir: "./"
}
});
});
// Default task
gulp.task('default', gulp.series('browser-sync', function() {
gulp.start('sass:watch');
}));
gulp.task('clean', function() {
return del(['dist']);
});
gulp.task('copyfonts', function() {
gulp.src('./node_modules/font-awesome/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
});
gulp.task('imagemin', function() {
return gulp.src('img/*.{png,jpg,gif}')
.pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
.pipe(gulp.dest('dist/img'));
});
gulp.task('usemin', function() {
return gulp.src('./*.html')
.pipe(flatmap(function(stream, file){
return stream
.pipe(usemin({
css: [ rev() ],
html: [ function() { return htmlmin({ collapseWhitespace: true })} ],
js: [ uglify(), rev() ],
inlinejs: [ uglify() ],
inlinecss: [ cleanCss(), 'concat' ]
}))
}))
.pipe(gulp.dest('dist/'));
});
gulp.task('build',gulp.series('clean', function() {
gulp.start('copyfonts','imagemin','usemin');
}));
The error I got is after running gulp build on the command line is:
[15:38:33] Starting 'build'...
[15:38:33] Starting 'clean'...
[15:38:33] Finished 'clean' after 69 ms
[15:38:33] Starting '<anonymous>'...
[15:38:33] '<anonymous>' errored after 3.57 ms
[15:38:33] TypeError: gulp.start is not a function
at C:\Users\HARIKA\Desktop\bootstrapassign1\Bootstrap4\conFusion\gulpfile.js
:74:10
[15:38:33] 'build' errored after 83 m
I dont know how to solve the erros. I even changed some of tasks to gulp.series() as per version of gulp version 4. Can anyone help me to resolve the error? Thank you in advance.
Replace these two tasks:
// Default task
gulp.task('default', gulp.series('browser-sync', function() {
gulp.start('sass:watch');
}));
gulp.task('build',gulp.series('clean', function() {
gulp.start('copyfonts','imagemin','usemin');
}));
with:
// Default task
gulp.task('default', gulp.series('browser-sync', 'sass:watch'));
gulp.task('build',gulp.series('clean', 'copyfonts','imagemin','usemin'));
gulp.start is not a part of gulp4+ - it was in v3 although not really sanctioned for use even there.
I had the same issue and perhaps found the solution:
Replace the following:
gulp.task('sass:watch', function () {
gulp.watch('./css/*.scss', ['sass']);
// Default task
gulp.task('default', gulp.series('browser-sync', function() {
gulp.start('sass:watch');
}));
And add instead:
gulp.task('sass:watch', function() {
gulp.watch('./css/*.scss', gulp.series(['sass']));
// Default task
gulp.task('default', gulp.parallel('browser-sync', 'sass:watch'));
From what I have found you will have to use gulp.series and gulp.parallel interchangeably with gulp +4.x
Now for the second part change:
gulp.task('copyfonts', function() {
gulp.src('./node_modules/font-awesome/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
});
Adding return here:
gulp.task('copyfonts', function() {
return gulp.src('./node_modules/font-awesome/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
});
And like shown in the previous answer make the last task:
gulp.task('build', gulp.series('clean','copyfonts','imagemin','usemin'));
Hope this helps!

Gulp task not finishing

Being new to gulp. I have the follwing task. I need to spawn a webserver and then another script has to run some stuff against this webserver. I am currently struggling with finishing the script because the browser-sync task does not finish and prevents the script from exit.
'use strict';
const browserSync = require('browser-sync').create();
const cp = require('child_process');
const minimalcss = require('minimalcss');
const gulp = require('gulp');
const clean = require('gulp-clean');
const sourceDir = "_site/";
const deployDir = "public/";
// build the mkdocs Site
gulp.task('build', function() {
return cp.exec('pipenv run mkdocs build --site-dir ' + sourceDir);
});
// Delete _deploy directory first
gulp.task('prepare', function() {
return gulp.src(deployDir, {read: false, allowEmpty: true})
.pipe(clean());
});
// Delete _deploy directory again // just for testing
gulp.task('cleanup', function() {
return gulp.src(deployDir, {read: false, allowEmpty: true})
.pipe(clean());
});
// does not lead to anything, just for testing
gulp.task('inlinecriticalCSS', function(done) {
minimalcss
.minimize({ urls: ['http://localhost:9999/' + 'index.html'] })
.then(result => {
console.log('OUTPUT', result.finalCss.length, result.finalCss);
})
.catch(error => {
console.error(`Failed the minimize CSS: ${error}`);
});
done();
});
// webserver
gulp.task('serve', (done) => {
browserSync.init({
port: 9999,
server: {
baseDir: sourceDir
}
});
done();
});
// default sequence
gulp.task('default', gulp.series(
'prepare',
'build',
'serve',
'inlinecriticalCSS',
'cleanup')
);

Conditionally running transform on browserify

I have added the babelify transformation and i've noticed that my mainScripts task now takes around 10 seconds instead of 0.5s as before.
I would therefore like to apply .transform("babelify", {presets: ["es2015"]}) only when the environment is or prod in order to speed up the task during development.
My function for determining the current environment
var isLocal = function() {
return argv.env === 'localdev' || argv.env === 'dev';
};
My scripts task:
gulp.task('mainScripts', function() {
return browserify('./app/app.js', {
debug: true
})
.transform("babelify", {presets: ["es2015"]})
.bundle()
.on('error', function(err) {
console.log(err.toString());
this.emit("end");
})
.pipe(source('main.js'))
.pipe(buffer())
.pipe(gulpif(!condition, sourcemaps.init({
loadMaps: true
})))
.pipe(ngAnnotate())
.pipe(gulpif(!condition, uglify({
mangle: true
}).on('error', gutil.log)))
.pipe(gulpif(!condition, sourcemaps.write('./')))
.pipe(gulp.dest('./dist/js/')).
pipe(gulpif(isLocal(), connect.reload()));
});
How can this be achieved?
The call to browserify returns the bundler and the transform call is just chained off that, so you can optionally call transform by doing something like this:
gulp.task('mainScripts', function() {
var bundler = browserify('./app/app.js', {
debug: true
});
if (!isLocal()) {
bundler = bundler.transform("babelify", { presets: ["es2015"] });
}
return bundler
.bundle()
.on('error', function(err) {
...
}
...
Alternatively, you could have a look for some gulp recipes for watchify, which should greatly improve your incremental build times.
How about using .plugin?
var babelify = function (b) {
return isLocal()
? b
: b.transform("babelify", {presets: ["es2015"]});
};
// .plugin(babelify)
browserify Plugins section says: plugin take the bundle instance as their first parameter
For some more advanced use-cases, a transform is not sufficiently extensible. Plugins are modules that take the bundle instance as their first parameter and an option hash as their second.
Applying plugin will be formatted like this:
var babelify = function (b) {
return isLocal()
? b
: b.transform("babelify", {presets: ["es2015"]});
};
gulp.task('mainScripts', function() {
return browserify('./app/app.js', {
debug: true
})
.plugin(babelify)
.bundle()
.on('error', function(err) {
...
}
...

Gulp with Browserify: Bundle task seems to fail after Delete task when watching

Here are my tasks to delete, bundle and watch for changes. Everytime I bundle, it works fine (even if the file doesn't exist yet). However, with the watch task, it'll break when it deletes the file and won't rebuild. Thoughts?
gulp.task('delete', function() {
var path = 'app/public/bundle.js';
return del(path);
});
gulp.task('bundle', ['delete'], function() {
var projectFiles = glob.sync('./app/**/*.js')
return browserify({
entries: projectFiles,
extensions: ['.js']
})
.bundle()
.on('error', function(err){
gutil.log(err);
})
.pipe(source('bundle.js'))
.pipe(gulp.dest('./app/public/'))
.pipe(notify({message: 'Browserify bundlified!'}))
});
gulp.task('watch', function(){
gulp.watch('app/assets/sass/**/*', ['css']);
gulp.watch('./app/**/*.js', ['bundle']);
})

How to minify webpack output using gulp?

I have this task:
gulp.task('js', function() {
var webpackConfig = extend({}, require('./webpack.config.dev.js'), {
devtool: "source-map",
});
return gulp.src(config.paths.mainJs)
//.pipe(beautify({indent: {value: ' '}}))
.pipe(named())
.pipe(webpack(webpackConfig))
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(through.obj(function (file, enc, cb) {
// Dont pipe through any source map files as it will be handled
// by gulp-sourcemaps
var isSourceMap = /\.map$/.test(file.path);
if (!isSourceMap) this.push(file);
cb();
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./deployment/deployment/js'))
.pipe(uglify())//JS_Parse_Error
The output of the previous pipe ./deployment/deployment/js/ is two files: bundle.js and bundle.js.map. So I think my pipe to uglify is wrong. How can I minify webpacks output?
All I had to do was modify my './webpack.config.dev.js` file already referenced in gulp to add the UglifyJsPlugin:
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: {
except: ['$super', '$', 'exports', 'require']
}
})
],