Gulp 4.0 version problem - parallel is not a function - node.js

I need help with my gulp project. Drops me error in terminal: TypeError: parallel is not a function Already searched information whole internet. Answer is to update Gulp version to 4.0.. Already updated. still shows the "parallel function" issue
My file:
const { src, dest, parallel, series, watch } = import('gulp');
const twig = import('gulp-twig');
const sass = import('gulp-sass');
const prefix = import('gulp-autoprefixer');
const data = import('gulp-data');
const sourcemaps = import('gulp-sourcemaps');
const concat = import('gulp-concat');
const plumber = import('gulp-plumber');
const browsersync = import('browser-sync');
const gulpcopy = import('gulp-copy');
const fs = import('fs');
const del = import('del');
const path = import('path');
var paths = {
build: {
html: 'dist/',
js: 'dist/assets/js/',
css: 'dist/assets/css/',
img: 'dist/assets/img/',
fonts: 'dist/assets/fonts/',
icons: 'dist/assets/icons/',
json: 'dist/assets/'
},
src: {
html: 'src/*.{htm,html,php}',
js: 'src/assets/js/*.js',
css: 'src/assets/sass/style.scss',
img: 'src/assets/img/**/*.*',
fonts: 'src/assets/fonts/**/*.*',
icons: 'src/assets/icons/**/*.*',
json: 'src/assets/*.json'
},
watch: {
html: 'src/**/*.{htm,html,php}',
js: 'src/assets/js/**/*.js',
css: 'src/assets/sass/**/*.scss',
img: 'src/assets/img/**/*.*',
fonts: 'src/assets/fonts/**/*.*',
icons: 'src/assets/icons/**/*.*',
json: 'src/assets/*.json'
},
clean: './dist'
};
// SCSS bundled into CSS task
function css() {
return src('client/scss/vendors/*.scss')
.pipe(sourcemaps.init())
// Stay live and reload on error
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(sass({
includePaths: [paths.src.css + 'vendors/'],
outputStyle: 'compressed'
}).on('error', function (err) {
console.log(err.message);
// sass.logError
this.emit('end');
}))
.pipe(prefix(['last 15 versions','> 1%','ie 8','ie 7','iOS >= 9','Safari >= 9','Android >= 4.4','Opera >= 30'], {
cascade: true
}))
//.pipe(minifyCSS())
.pipe(concat('bootstrap.min.css'))
.pipe(sourcemaps.write('.'))
.pipe(dest('build/assets/css'));
}
// JS bundled into min.js task
function js() {
return src('dist/js/*.js')
.pipe(sourcemaps.init())
.pipe(concat('scripts.min.js'))
.pipe(sourcemaps.write('.'))
.pipe(dest('build/assets/js'));
}
function twigTpl () {
return src(['./dist/templates/*.twig'])
// Stay live and reload on error
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
// Load template pages json data
.pipe(data(function (file) {
return JSON.parse(fs.readFileSync(paths.data + path.basename(file.path) + '.json'));
}).on('error', function (err) {
process.stderr.write(err.message + '\n');
this.emit('end');
})
)
// Load default json data
.pipe(data(function () {
return JSON.parse(fs.readFileSync(paths.data + path.basename('default.twig.json')));
}).on('error', function (err) {
process.stderr.write(err.message + '\n');
this.emit('end');
})
)
// Twig compiled
.pipe(twig()
.on('error', function (err) {
process.stderr.write(err.message + '\n');
this.emit('end');
})
)
.pipe(dest(paths.build));
}
function copyAssets() {
// Copy assets
return src(['./dist/assets/**/*.*','!./dist/assets/**/*.psd','!./dist/assets/**/*.*.map'],
del(paths.build + 'assets/**/*')
)
.pipe(gulpcopy(paths.build + 'assets', { prefix: 2 }));
}
// BrowserSync
function browserSync() {
browsersync({
server: {
baseDir: paths.build
},
notify: false,
browser: "google chrome",
// proxy: "0.0.0.0:5000"
});
}
// BrowserSync reload
function browserReload () {
return browsersync.reload;
}
// Watch files
function watchFiles() {
// Watch SCSS changes
watch(paths.scss + '**/*.scss', parallel(css))
.on('change', browserReload());
// Watch javascripts changes
watch(paths.js + '*.js', parallel(js))
.on('change', browserReload());
// Watch template changes
watch(['dist/templates/**/*.twig','dist/data/*.twig.json'], parallel(twigTpl))
.on('change', browserReload());
// Assets Watch and copy to build in some file changes
watch('dist/assets/**/*')
.on('change', series(copyAssets, css, css_vendors, js, browserReload()));
}
const watching = parallel(watchFiles, browserSync);
exports.js = js;
exports.css = css;
exports.default = parallel(copyAssets, css, js, twigTpl);
exports.watch = watching;
My gulp version:
"node": "18.12.1"
"gulp": "^4.0.2",
On terminal when i write gulp -v it shows:
CLI version: 2.3.0
Local version: 4.0.2
Expecting professional help

Since your gulpfile is a CommonJS module, use require instead of import:
const { src, dest, parallel, series, watch } = require('gulp');
const twig = require('gulp-twig');
const sass = require('gulp-sass');
const prefix = require('gulp-autoprefixer');
const data = require('gulp-data');
const sourcemaps = require('gulp-sourcemaps');
const concat = require('gulp-concat');
const plumber = require('gulp-plumber');
const browsersync = require('browser-sync');
const gulpcopy = require('gulp-copy');
const fs = require('fs');
const del = require('del');
const path = require('path');
Using an ESM style gulpfile is also an option, but it's not as simple as just replacing require with import (btw the syntax is import sass from 'gulp-sass';...), you will also need to rename the file to "gulpfile.mjs", change the style of your exports, and probably more.

Related

Create javascript resource file from local files

I'm using gulp and I trying to create a gulp task that combine files in a javascript file.
For example, image I have this:
File template\template1.html :
<h2>some html content</h2>
<p>blah blah blah</p>
File template\template2.html :
<h2>some other html content</h2>
<img src='cat.png'>
I'd like to read and merge these files into a single javascript file like this :
const templates = {
"template1" : "<h2>some html content</h2>\n<p>blah blah blah</p>",
"template2" : "<h2>some other html content</h2>\n<img src='cat.png'>"
}
export default templates
However, I'm failing when dealing with gulp plumbing (I'm quite new to gulp I admit).
How to reach my goal ?
Right now I tried to play with gulp-trough, but it fails at execution:
const gulp = require('gulp');
const through = require('gulp-through');
gulp.task('templates', function () {
var result = {}
gulp.src('src/templates/**/*.html')
.pipe(through('readFile', function(){
console.log(arguments); // not reached!
}, defaults));
})
gulp.task('default', ['templates'])
It shouldn't be hard to write your own plugin using through2 module (as explained in official docs.)
// gulpfile.js
const gulp = require('gulp');
const path = require('path');
const through = require('through2'); // npm install --save-dev through2
const toTemplateModule = obj => {
return [
`const template = ${JSON.stringify(obj, null, 2)};`,
'',
'export default template;'
].join('\n');
};
const mergeTemplate = file => {
const results = {};
let latestFile;
return through.obj(
function(file, encoding, callback) {
latestFile = file;
results[path.basename(file.path)] = file.contents.toString(encoding);
callback(null, file);
},
function(callback) {
const joinedFile = latestFile.clone({
contents: false
});
joinedFile.path = path.join(latestFile.base, file);
joinedFile.contents = Buffer.from(toTemplateModule(results), 'utf-8');
this.push(joinedFile);
callback();
});
};
gulp.task('templates', () => {
return gulp
.src('./src/templates/**/*.html')
.pipe(mergeTemplate('templates.js'))
.pipe(gulp.dest('./build'))
});
gulp.task('default', ['templates'])

livereload - Image is not resize immediately after uploading

I have created gulp tasks scheduler for JavaScript minification and image resizing. All things work nicely when I executes command manually.
Command:
gulp
But when I include gulp-livereload module to perform operation automatically, Command line watch continuously when I upload images, it does not resize.
Just cursor is blinking. When uploads an image, no activities display in command watch list.
gulpfile.js
// include gulp
var gulp = require('gulp');
// include plug-ins
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var stripDebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var imageresize = require('gulp-image-resize');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
var liveReload = require("gulp-livereload");
// JS hint task
gulp.task('jshint', function () {
gulp.src([
'./app/client/app.js',
'./app/client/app.routes.js',
'./app/client/modules/**/controllers/*.js',
'./app/client/modules/**/directives/*.js',
'./app/client/modules/**/services/*.js',
'./app/client/services/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(liveReload());
});
gulp.task('jsminification', function () {
gulp.src([
'./app/client/app.js',
'./app/client/app.routes.js',
'./app/client/modules/**/controllers/*.js',
'./app/client/modules/**/directives/*.js',
'./app/client/modules/**/services/*.js',
'./app/client/modules/**/filter/*.js',
'./app/client/services/*.js'])
.pipe(concat('script.js'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(gulp.dest('./app/build/scripts/'))
.pipe(liveReload());
});
gulp.task('resize', function () {
// set the folder name and the relative paths
// in the example the images are in ./assets/images
// and the public directory is ../public
var paths = {
folder: 'media/',
src: './app/client/',
dest: './app/client/resize/'
};
// create an array of image groups (see comments above)
// specifying the folder name, the ouput dimensions and
// whether or not to crop the images
var images = [
// {folder: 'bg', width: 1200, crop: false},
{folder: 'photo', width: 120, height: 120, crop: true},
//{folder: 'projects', width: 800, height: 500, crop: true}
];
console.log("resize called");
// loop through image groups
images.forEach(function (type) {
console.log(type);
var source_ = paths.src + paths.folder + type.folder + '/*';
var scale_ = type.width + "x" + type.height + "/";
//var destination_ = paths.dest + paths.folder + scale_ + type.folder;
var destination_ = paths.dest + scale_ + type.folder;
console.log(">source:" + source_);
console.log(">scale:" + scale_);
console.log(">destination:" + destination_);
// build the resize object
var resize_settings = {
width: type.width,
crop: type.crop,
// never increase image dimensions
upscale: false
}
// only specify the height if it exists
if (type.hasOwnProperty("height")) {
resize_settings.height = type.height;
}
gulp
// grab all images from the folder
.src(source_)
// resize them according to the width/height settings
.pipe(imageresize(resize_settings))
// output each image to the dest path
// maintaining the folder structure
.pipe(gulp.dest(destination_))
.pipe(liveReload());
});
});
gulp.task('watch', function () {
liveReload.listen({host: process.env['HOST'], port: process.env['PORT']});
gulp.watch('./app/client/media/photo/*.{png,jpg,jpeg}', ['resize']);
});
gulp.task('default', ['jshint', 'jsminification', 'resize', 'watch']);
I want to resize image automatically as new image uploads in photo folder.
After some R&D I have found following solution using "gulp-watch" module and it works fine.
// include gulp
var gulp = require('gulp');
// include plug-ins
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var stripDebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var imageresize = require('gulp-image-resize');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');
var watch = require("gulp-watch");
var newer = require("gulp-newer");
var paths = {
folder: 'media/',
src: './app/client/',
dest: './app/client/resize/'
}
var images = [
{folder: 'photo', width: 120, height: 120, crop: true},
];
// JS hint task
gulp.task('jshint', function () {
gulp.src([
'./app/client/app.js',
'./app/client/app.routes.js',
'./app/client/modules/**/controllers/*.js',
'./app/client/modules/**/directives/*.js',
'./app/client/modules/**/services/*.js',
'./app/client/services/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
// JS minification task
gulp.task('jsminification', function () {
gulp.src([
'./app/client/app.js',
'./app/client/app.routes.js',
'./app/client/modules/**/controllers/*.js',
'./app/client/modules/**/directives/*.js',
'./app/client/modules/**/services/*.js',
'./app/client/modules/**/filter/*.js',
'./app/client/services/*.js'])
.pipe(concat('script.js'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(gulp.dest('./app/build/scripts/'));
});
// image resize
gulp.task('resize', function () {
// loop through image groups
images.forEach(function (type) {
var source_ = paths.src + paths.folder + type.folder + '/*';
var scale_ = type.width + "x" + type.height + "/";
//var destination_ = paths.dest + paths.folder + scale_ + type.folder;
var destination_ = paths.dest + scale_ + type.folder;
// build the resize object
var resize_settings = {
width: type.width,
crop: type.crop,
// never increase image dimensions
upscale: false
}
// only specify the height if it exists
if (type.hasOwnProperty("height")) {
resize_settings.height = type.height;
}
gulp
// grab all images from the folder
.src(source_)
.pipe(newer(destination_))
// resize them according to the width/height settings
.pipe(imageresize(resize_settings))
// optimize the images
.pipe(imagemin({
progressive: true,
// set this if you are using svg images
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
// output each image to the dest path
// maintaining the folder structure
.pipe(gulp.dest(destination_));
});
});
// Gulp default task
gulp.task('default', ['jshint', 'jsminification', 'resize'], function () {});
// Gulp watch for new image resizing
watch('./app/client/media/photo/*.+(png|jpg|jpeg|gif)', function () {
gulp.run('resize');
});

How to load contents of an external file into gulp browser-sync

I am loading browser-sync proxy and want to load search and replace terms from an external file in order to amend the page as it is loaded into a browser.
The reason I want to load the search and replace terms from a separate file is because I want to make use of gulp-watch and reload browser-sync as the search and replace terms are updated.
My Project folder:
regex/search.txt <- search term is stored in this file
regex/replace.txt <- replace term is stored in this file
gulpfile.js
Contents of gulpfile.js:
var gulp = require('gulp'),
fs = require("fs"),
browserSync = require('browser-sync');
var proj_url = "http://www.example.com";
var search_text = "";
var replace_text = "";
gulp.task('readRegEx', function() {
return gulp.src('regex/*.txt')
.pipe(fs.readFile("regex/search.txt", "utf-8", function(err, data) {
search_text = data;
}))
.pipe(fs.readFile("regex/replace.txt", "utf-8", function(err, data) {
replace_text = data;
}))
});
gulp.task('browser-sync', function() {
browserSync({
proxy: {
target: proj_url
},
rewriteRules: [
{
match: search_text,
fn: function (match) {
return replace_text;
}
}
]
});
});
gulp.task('default', ['readRegEx','browser-sync'], function() {
gulp.watch(['regex/*.txt'], [browserSync.reload]);
});
This doesn't work. I get the following error:
TypeError: Cannot call method 'on' of undefined ...
For that to work you need to make browser-sync dependant in readRegEx
gulp.task('browser-sync', ['readRegEx'], function() {
this guarantees the proper execution order.
then you can make readRegEx sync (and simpler) this way:
gulp.task('readRegEx', function() {
search_text = fs.readFileSync("regex/search.txt", "utf-8").toString();
replace_text = fs.readFileSync("regex/replace.txt", "utf-8").toString();
});

Using gulp-watch with babel.js

Below is a Gulp ES6 transpilation task. It works fine, but I'm trying to replace gulp.watch with the gulp-watch plugin so new files will be caught. The problem is that gulp-watch isn't giving me what gulp.watch does in the callback, and I'm not sure what to do about it.
Here's my original working task:
var gulp = require('gulp'),
rename = require('gulp-rename'),
plumber = require('gulp-plumber'),
gprint = require('gulp-print'),
notify = require('gulp-notify'),
babel = require('gulp-babel');
gulp.task('default', function() {
return gulp.watch('../**/**-es6.js', function(obj){
if (obj.type === 'changed') {
gulp.src(obj.path, { base: './' })
.pipe(plumber({
errorHandler: function (error) { /* elided */ }
}))
.pipe(babel())
.pipe(rename(function (path) {
path.basename = path.basename.replace(/-es6$/, '');
}))
.pipe(gulp.dest(''))
.pipe(gprint(function(filePath){ return "File processed: " + filePath; }));
}
});
});
And here's all that I have so far with gulp-watch:
var gulp = require('gulp'),
rename = require('gulp-rename'),
plumber = require('gulp-plumber'),
gprint = require('gulp-print'),
notify = require('gulp-notify'),
babel = require('gulp-babel'),
gWatch = require('gulp-watch');
gulp.task('default', function() {
return gWatch('../**/**-es6.js', function(obj){
console.log('watch event - ', Object.keys(obj).join(','));
console.log('watch event - ', obj.event);
console.log('watch event - ', obj.base);
return;
if (obj.type === 'changed') {
gulp.src(obj.path, { base: './' })
.pipe(plumber({
errorHandler: function (error) { /* elided */ }
}))
.pipe(babel())
.pipe(rename(function (path) {
path.basename = path.basename.replace(/-es6$/, '');
}))
.pipe(gulp.dest(''))
.pipe(gprint(function(filePath){ return "File processed: " + filePath; }));
}
});
});
The output of the logging is this:
watch event - history,cwd,base,stat,_contents,event
watch event - change
watch event - ..
How do I get gulp-watch to give me the info I had before, or, how can I change my task's code to get this working again with gulp-watch?
According to the tests, obj.relative should contain the relative filename, and obj.path will still hold the absolute file path, just as it did in your original code. Also, the callback accepts a Vinyl object, which is documented here: https://github.com/wearefractal/vinyl
You probably can't see them in your logs since Object.keys doesn't enumerate properties in the prototype chain.
Using a for..in loop, you should be able to see all the properties.

Gulp stops watching

I'm using gulp to watch certain files and run certain tasks however after the first few runs it seems to stop watching. If I save html files in the pages directory, after the first two to five updates, the templates task seems to stop running. I've included my gulpfile below.
// Include gulp
var gulp = require('gulp');
// Include plugins
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var notify = require('gulp-notify')
var htmlv = require('gulp-html-validator')
var swig = require('gulp-swig');
var plumber = require('gulp-plumber');
// Linting
gulp.task('lint', function() {
return gulp.src('js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('sass', function() {
return gulp.src('./resources/scss/*.scss')
.pipe(sass()
.on('error', notify.onError(function(error) {
return 'Error: ' + error.message;
}))
)
.pipe(gulp.dest('./css'));
});
gulp.task('validate', function() {
return gulp.src('./**.html')
.pipe(htmlv({format: 'xhtml'}))
.pipe(gulp.dest('./validation_out'));
});
gulp.task('watch', function() {
gulp.watch('js/*.js', ['lint']);
gulp.watch('./resources/scss/*.scss', ['sass']);
gulp.watch('./pages/*.html', ['templates']);
});
gulp.task('templates', function() {
return gulp.src('./pages/*.html')
.pipe(swig({
load_json: true,
defaults: {
cache: false
}
}
))
.pipe(gulp.dest('.'));
});
gulp.task('default', ['lint', 'sass', 'templates', 'watch']);

Resources