Gulpfile.js Throws exception for wrench default implemented method of readdirSyncRecursive while calling require function of node.js - gulp

i am new to Gulp and specially Gulp 4. here i have my gulpfile.js
/**
* Welcome to your gulpfile!
* The gulp tasks are splitted in several files in the gulp directory
* because putting all here was really too long
*/
'use strict';
var gulp = require('gulp');
var wrench = require('wrench');
/**
* This will load all js or coffee files in the gulp directory
* in order to load all gulp tasks
*/
wrench.readdirSyncRecursive('./gulp').filter(function(file) {
return (/\.(js|coffee)$/i).test(file);
}).map(function(file) {
require('./gulp/' + file);
});
/**
* Default task clean temporaries directories and launch the
* main optimization build task
*/
gulp.task('default', ['clean'], function () {
gulp.start(['build']);
});
function done() {
}
while trying to run => gulp build i am facing following Exception
AssertionError [ERR_ASSERTION]: Task function must be specified
at Gulp.set [as _setTask] (C:\Users\ahsan\Documents\dev-work\smsvoltapp\node_modules\undertaker\lib\set-task.js:10:3)
at Gulp.task (C:\Users\ahsan\Documents\dev-work\smsvoltapp\node_modules\undertaker\lib\task.js:13:8)
at Object.<anonymous> (C:\Users\ahsan\Documents\dev-work\smsvoltapp\gulp\build.js:28:6)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Module.require (node:internal/modules/cjs/loader:1061:19)
at require (node:internal/modules/cjs/helpers:103:18)
at C:\Users\ahsan\Documents\dev-work\smsvoltapp\gulpfile.js:19:3 {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '=='
}
It seems the node.js function require at line 19:3 is not upto the mark and valid for gulp4
Gulp version:
CLI version: 2.3.0
Local version: 4.0.2
npm -v => 8.19.2
Please help

Related

Error on gulp build during migration from gulp v3 to v4

I've tried to migrate from gulp v3 to v4, according to my researches, I should change my gulpfile.js file.
So, I tried it like this:
gulp.task('clean-css', function (cb) {
return rimraf(paths.css, cb);
});
to
gulp.task('clean-css', gulp.series(function (cb) {
return rimraf(paths.css, cb);
}));
-----------------------------------------------------------------
gulp.task('clean', ['clean-css', 'clean-fonts', 'clean-js']);
to
gulp.task('clean', gulp.parallel('clean-css', 'clean-fonts', 'clean-js'));
-----------------------------------------------------------------
gulp.task('build-css', ['lint-css'], function () {});
to
gulp.task('build-css', gulp.series('lint-css', function () {}));
but when I write 'gulp build' I get such error
D:\Projects\Exo\exo\src\COG.SRM\node_modules\undertaker\lib\helpers\normalizeArgs.js:20
assert(flattenArgs.length, 'One or more tasks should be combined using series or parallel');
^
AssertionError [ERR_ASSERTION] [ERR_ASSERTION]: One or more tasks should be combined using series or parallel
at normalizeArgs (D:\Projects\Exo\exo\src\COG.SRM\node_modules\undertaker\lib\helpers\normalizeArgs.js:20:3)
at Gulp.series (D:\Projects\Exo\exo\src\COG.SRM\node_modules\undertaker\lib\series.js:13:14)
at Object. (D:\Projects\Exo\exo\src\COG.SRM\gulpfile.js:383:24)
at Module._compile (internal/modules/cjs/loader.js:936:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
at Module.load (internal/modules/cjs/loader.js:790:32)
at Function.Module._load (internal/modules/cjs/loader.js:703:12)
at Module.require (internal/modules/cjs/loader.js:830:19)
at require (internal/modules/cjs/helpers.js:68:18)
at execute (C:\Users\SS\AppData\Roaming\npm\node_modules\gulp\node_modules\gulp-cli\lib\versioned\^4.0.0\index.js:36:18)
Could someone help me, please?

Browserify - ParseError: 'import' and 'export' may appear only with 'sourceType: module

In my gulpfile I have
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var sass = require('gulp-sass');
var babel = require("gulp-babel");
var rename = require('gulp-rename');
var source = require('vinyl-source-stream');
var browserify = require('gulp-browserify');
var notify = require("gulp-notify");
gulp.task('js', function () {
gulp.src('js/main.js')
.pipe(babel())
.pipe(browserify())
.on('error', errorAlert)
.pipe(rename('./dist/js/bundle.js'))
//.pipe(uglify())
.pipe(gulp.dest('./'))
.pipe(notify({title: "Success", message: "Well Done!", sound: "Glass"}));
})
and in my app.js I am trying to import but get the errror
import SimpleBreakpoints from 'simple-breakpoints'
Any idea how to get rid of the error and use the import syntax?
Edit: the .babelrc
{
"presets": ["es2015"],
}
In your configuration, you pipe js/main.js to Babel, so that's the only file that will be transpiled. When Browserify requires app.js, it will seen ES6 content and will effect the error you are seeing.
You could use Babelify to solve the problem. It's a Browserify transform that will transpile the source that Browserify receives.
To install it, run this command:
npm install babelify --save-dev
And to configure it, change your task to:
gulp.task('js', function () {
gulp.src('js/main.js')
.pipe(browserify({ transform: ['babelify'] }))
.on('error', errorAlert)
.pipe(rename('./dist/js/bundle.js'))
//.pipe(uglify())
.pipe(gulp.dest('./'))
.pipe(notify({ title: "Success", message: "Well Done!", sound: "Glass" }));
})
Browserify in Gulp
For those who work with gulp and want to transpile ES6 to ES5 with browserify, you might stumble upon gulp-browserify plug-in. Warning as it is from version 0.5.1 gulp-browserify is no longer suported!!!. Consequences, of this action and transpiling with gulp-browserify will result with source code that might produce errors such as the one in question or similar to these: Uncaught ReferenceError: require is not defined or Uncaught SyntaxError: Unexpected identifier next to your import statements e.g. import * from './modules/bar.es6.js';
Solution
Althoutg gulp-browserify recomends to "checkout the recipes by gulp team for reference on using browserify with gulp". I found this advice to no avail. As it is now (2st July 2019) solution that worked for me was to replace gulp-browserify with gulp-bro#1.0.3 plug-in. This successfully, transpired ES6 to ES5 (as it is now) - It might change in future since support for JavaSript libraries decays with time of it appearance.
Assumption: To reproduce this solution you should have installed docker. Beside that you should be familiar with babel and babelify.
Source Code
This solution was successfully reproduced in docker environment, run node:11.7.0-alpine image.
Project Structure
/src <- directory
/src/app/foo.es6.js
/src/app/modules/bar.es6.js
/src/app/dist <- directory
/src/app/dist/app.es5.js
/src/gulpfile.js
/src/.babelrc
/src/package.json
/src/node_modules <- directory
Step 1: Run docker image
$ docker run --rm -it --name bro_demo node:11.7.0-alpine ash
Step 2: Create directories and source files
$ mkdir -p /src/dist
$ mkdir -p /src/app/modules/
$ touch /src/app/foo.es6.js
$ touch /src/app/modules/bar.es6.js
$ touch /src/gulpfile.js
$ touch /src/.babelrc
$ touch /src/package.json
$ cd /src/
$ apk add vim
.babelrc
{
"presets": ["#babel/preset-env"]
}
package.json
{
"name": "src",
"version": "1.0.0",
"description": "",
"main": "",
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.4.5",
"#babel/preset-env": "^7.4.5",
"babelify": "^10.0.0",
"gulp": "^4.0.2",
"gulp-bro": "^1.0.3",
"gulp-rename": "^1.2.2"
}
}
bar.es6.js
"use strict"
class Bar {
constructor(grammar) {
console.log('Bar time!');
}
}
export default Bar;
foo.es6.js
"use strict"
import Bar from './modules/bar.es6.js';
class Foo {
constructor(grammar) {
console.log('Foo time!');
}
}
var foo = new Foo()
var bar = new Bar()
gulpfile.js
const bro = require('gulp-bro');
const gulp = require('gulp');
const rename = require('gulp-rename');
const babelify = require('babelify');
function transpileResources(callback) {
gulp.src(['./app/foo.es6.js'])
.pipe(bro({transform: [babelify.configure({ presets: ['#babel/preset-env'] })] }))
.pipe(rename('app.es5.js'))
.pipe(gulp.dest('./dist/'));
callback();
}
exports.transpile = transpileResources;
Step 3 - Transpile ES6 to ES5
$ npm install
$ npm install -g gulp#4.0.2
$ gulp transpile
[09:30:30] Using gulpfile /src/gulpfile.js
[09:30:30] Starting 'transpile'...
[09:30:30] Finished 'transpile' after 9.33 ms
$ node dist/app.es5.js
Foo time!
Bar time!
Source code after transpilation app.es5.js
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
var _barEs = _interopRequireDefault(require("./modules/bar.es6.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Foo = function Foo(grammar) {
_classCallCheck(this, Foo);
console.log('Foo time!');
};
var foo = new Foo();
var bar = new _barEs["default"]();
},{"./modules/bar.es6.js":2}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Bar = function Bar(grammar) {
_classCallCheck(this, Bar);
console.log('Bar time!');
};
var _default = Bar;
exports["default"] = _default;
},{}]},{},[1]);
Simply switching to webpack instead of browserify fixed the issue for me.
var webpack = require('webpack-stream')
gulp.task('default', function () {
return gulp.src('src/source.js')
.pipe(webpack({
output: {
filename: 'app.js'
}
}))
.pipe(gulp.dest('dist/app.js'))
})

gulp-image-optimization build gives error

My Node and Npm Vesrions are below
node v6.9.1
npm v3.10.9
My code is
'use strict';
const gulp = require('gulp');
const imageop = require('gulp-image-optimization');
let dir = {
srcImages: 'public/wps/source/images',
build: 'public/wps/build/'
};
const config = {
src: dir.srcImages + '/**/*',
dest: dir.build + 'images/'
};
gulp.task('img-prod', function (cb) {
gulp.src(config.src).pipe(imageop({
optimizationLevel: 5,
progressive: true,
interlaced: true
})).pipe(gulp.dest(config.dest)).on('end', cb).on('error', cb);
});
When i do gulp build it throws an error
internal/child_process.js:289
var err = this._handle.spawn(options);
^
TypeError: Bad argument
at TypeError (native)
at ChildProcess.spawn (internal/child_process.js:289:26)
at exports.spawn (child_process.js:380:9)
at Imagemin._optimizeJpeg (/Users/sureshraju/xxx/Wps/web-pres/node_modules/image-min/imagemin.js:126:12)
at Imagemin.optimize (/Users/sureshraju/xxxx/Wps/web-pres/node_modules/image-min/imagemin.js:57:26)
at module.exports (/Users/sureshraju/xxxx/Wps/web-pres/node_modules/image-min/imagemin.js:179:21)
at /Users/sureshraju/xxxx/Wps/web-pres/node_modules/gulp-image-optimization/index.js:38:17
at FSReqWrap.oncomplete (fs.js:123:15)
Do you have svg files in your source directory?
I have just been getting the exact same problem in a project I have picked up from someone else.
I omitted svg files from the glob and the task then ran without errors.

Gulp tasks defined into a dependency module are not reachable

I have tasks I would like to share across several projects, so I moved them inside another module, which I load from my target project's gulpfile.js.
Project A tree:
gulpfile.js
package.json
...
gulpfile.js:
require('my-gulp-tasks')({
version: '0.0.1',
production: utils.env.production,
port: ...
// misc settings to customize tasks
});
My gulp tasks module tree:
index.js
tasks/
clean.js
assets.js
...
index.js (simplified version):
var gulp = require('gulp');
module.exports = function (settings) {
//...
gulp.task('clean', require('./tasks/clean')(settings));
return gulp;
}
But when I ask for the known tasks from within "Project A" with gulp -T, the command's output is empty...
What am I missing?
I finally got it working by passing a gulp instance from the gulpfile to the module, and avoiding to require gulp locally.
I ended up with:
Project A:
gulpfile.js:
var gulp = require('gulp');
require('my-gulp-tasks')(gulp, {
// settings...
});
My gulp tasks module:
index.js:
module.exports = function (gulp, settings) {
//...
gulp.task('clean', require('./tasks/clean')(settings));
return gulp;
}
clean.js:
var rm = require('gulp-rm');
module.exports = function (gulp) {
return function () {
return gulp.src('dist/**/*').pipe(rm());
};
};

Run eslint before watchify runs

I'm adding watchify to our build process but I want to put a precondition to watchify running, and that is that the file(s) that changed pass our linting step (which is using ESLint).
I was thinking of doing this:
function runBrowserify(watch){
var babel = babelify.configure({
optional: ['es7.objectRestSpread']
});
var b = browserify({
entries: './app/main.js',
debug: true,
extensions: ['.jsx', '.js'],
cache: {},
packageCache: {},
fullPaths: true
})
.transform(babel);
if(watch) {
// if watch is enable, wrap this bundle inside watchify
b = watchify(b);
b.on('update', function(ids) {
//run the linting step
lint(ids);
//run the watchify bundle step
gutil.log(gutil.colors.blue('watchify'), 'Started');
bundleShare(b);
});
b.on('time', function (time) {
gutil.log(gutil.colors.blue('watchify'), 'Finished', 'after', gutil.colors.magenta(time), gutil.colors.magenta('ms'));
});
}
bundleShare(b);
}
function bundleShare(b) {
b.bundle()
.pipe(source('main.min.js'))
.pipe(gulp.dest('./dist'));
}
function lint(glob) {
return gulp.src(glob)
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError());
}
The problem is that the linting step is async so it doesn't finish before the bundling would be done (it also throws so I probably need to use plumber to stop it from terminating the watch step).
So how would I make a precondition before I call bundleShared?
I was able to do this using the closure method I mentioned above. I also moved my Browserify and Watchify code into helper functions that each build could take advantage of.
gulpfile.js (partial)
gulp.task('build:dev', buildDev);
gulp.task('lint:js', lintJS);
function lintJS(callback) {
return gulp.src(['src/**/*.js', 'src/**/*.jsx', '!src/js/vendor/**/*.*',])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
}
function buildDev(callback) {
var bundler = getBundler('src/js/app.jsx', { debug: true }, callback);
var watcher = getWatcher(bundler, rebundle);
function rebundle() {
lintJS(callback);
return watcher.bundle()
.pipe(source('bundle.min.js'))
.pipe(buffer())
.pipe(gulp.dest('dist/js'));
}
rebundle();
// Call watch methods here, i.e.: watchHTML()
return callback();
}
/****************************** Helper functions ******************************/
/**
* Gets the default Browserify bundler used by all builds.
*
*
* #param path A string representing where Browserify should start from
* #param options An Object containing options for the bundler
* #param callback The Gulp callback function from the calling task
* #return A basically configured Browserify bundler
*/
function getBundler(path, options, callback) {
var bundler = browserify(path, { debug: options.debug, cache: {}, packageCache: {} });
bundler.transform(babelify);
bundler.on('log', gutil.log);
bundler.on('error', gutil.log.bind(gutil.colors.red, 'Browserify Error'));
return bundler;
}
/**
* Gets the default Watchify watcher used by dev builds. By default, the watcher
* will rebundle the Browserify package when an update occurs.
*
* #param bundle The Browserify bundler object
* #param rebundle A function to perform when Watchify detects a code update
* #return A basically configured Watchify watcher
*/
function getWatcher(bundle, rebundle) {
var watcher = watchify(bundle);
watcher.on('update', rebundle);
return watcher;
}
For my test and prod builds, I don't use Watchify (and thus have no rebundle() method) so I keep the 'lint:js' task as a dependency:
gulp.task('build:test', ['lint:js'], buildTest);
gulp.task('build:prod', ['lint:js'], buildProd);