Gulp task not finishing - gulp

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

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!

Using Gulp watch, Axios and Browsersync to do an HTTP get before reloading browser on file change

I'm trying to watch 2 sets of folders. One set just requires a browser reload on change. The second requires "reinitializing the framework", via a separate, background http get before doing the reload.
My current attempt handles this properly once, but only once. Can you tell me both why and how to fix it? The troublesome portion is in the second watch task.
const gulp = require('gulp');
const axios = require("axios");
const bs = require('browser-sync').create();
const { reload } = bs;
const url = "http://127.0.0.1:80/healthcheck?fwreinit=1";
var paths = {
refresh: [
"./layouts/**/*.*",
"./views/**/*.*",
"./includes/**/*.js",
"./includes/**/*.css"
],
reinit: [
"./handlers/**/*.*",
"./models/**/*.*",
"./interceptors/**/*.*",
"./config/**/*.*"
]
}
gulp.task('watch', () => {
gulp.watch(paths.refresh, (done) => {
reload();
done();
});
gulp.watch(paths.reinit, () => {
console.log("Reinitializing framework");
axios.get(url)
.then(response => {
console.log(response.data.trim());
reload();
})
.catch(error => {
console.log("Error: Please ensure you have a /healthcheck route set up in /config/router.cfc!");
console.log("Error: Once you've done that, please shut down commandbox then try browsersync again.");
});
});
});
gulp.task('proxy', () => {
bs.init({
proxy: "localhost:80",
port: 81,
open: true,
notify: false
});
});
gulp.task('default', gulp.parallel('watch', 'proxy'));
Gulp watch passes a "done" callback that must be called in order to proceed. Changing the code to the following solved the problem.
const gulp = require('gulp');
const axios = require("axios");
const bs = require('browser-sync').create();
const { reload } = bs;
const url = "http://127.0.0.1:80/healthcheck?fwreinit=1";
var paths = {
refresh: [
"./layouts/**/*.*",
"./views/**/*.*",
"./includes/**/*.js",
"./includes/**/*.css"
],
reinit: [
"./handlers/**/*.*",
"./models/**/*.*",
"./interceptors/**/*.*",
"./config/**/*.*"
]
}
gulp.task('watch', () => {
gulp.watch(paths.refresh, (done) => {
reload();
done();
});
gulp.watch(paths.reinit, (done) => {
console.log("Reinitializing framework");
axios.get(url)
.then(response => {
console.log(response.data.trim());
reload();
done();
})
.catch(error => {
console.log("Error: Please ensure you have a /healthcheck route set up in /config/router.cfc!");
console.log("Error: Once you've done that, please shut down commandbox then try browsersync again.");
});
});
});
gulp.task('proxy', () => {
bs.init({
proxy: "localhost:80",
port: 81,
open: true,
notify: false
});
});
gulp.task('default', gulp.parallel('watch', 'proxy'));

Gulp 4 tasks do not run in parallel

I have migrated from gulp 3 to 4. Everything was fine for a week, and then my build pipeline broke. I have a hugo website that should be rebuilt on gulp build.
The build task calls three other tasks in parallel: gulp.parallel("css", "js", "hugo");
When running gulp build, gulp claims it succeeded in 2.19 ms, which is too fast. These three task are supposed to output files to my dist folder, but it does not run my tasks at all.
Running the css, js, and hugo tasks manually in the terminal works as expected.
I am fairly new to gulp 4, so I suspect I am missing some detail. Here is my gulpfile:
import gulp from "gulp";
import cp from "child_process";
import gutil from "gulp-util";
import postcss from "gulp-postcss";
import cssImport from "postcss-import";
import cssnext from "postcss-cssnext";
import BrowserSync from "browser-sync";
import webpack from "webpack";
import webpackConfig from "./webpack.conf";
import cssnano from "cssnano";
import imagemin from "gulp-imagemin";
import imageminMozjpeg from "imagemin-mozjpeg";
import webp from "imagemin-webp";
import gm from "gulp-gm";
const browserSync = BrowserSync.create();
const hugoBin = `./bin/hugo.${process.platform === "win32" ? "exe" : process.platform}`;
const defaultArgs = ["-d", "../dist", "-s", "site"];
if (process.env.DEBUG) {
defaultArgs.unshift("--debug");
}
const hugo = (cb) => {
buildSite(cb);
};
const hugoPreview = (cb) => {
buildSite(cb, gulp.parallel("--buildDrafts", "--buildFuture"));
cb();
};
const build = (cb) => {
gulp.parallel("css", "js", "hugo");
cb();
};
const buildPreview = (cb) => {
gulp.parallel("css", "js", "hugoPreview");
cb();
};
const css = (cb) => {
gulp.src("./src/css/*.css")
.pipe(postcss([
cssImport({
from: "./src/css/main.css"
}),
cssnext(),
cssnano(),
]))
.pipe(gulp.dest("./dist/css"))
.pipe(browserSync.stream());
cb();
};
const js = (cb) => {
const myConfig = Object.assign({}, webpackConfig);
webpack(myConfig, (err, stats) => {
if (err) throw new gutil.PluginError("webpack", err);
gutil.log("[webpack]", stats.toString({
colors: true,
progress: true
}));
browserSync.reload();
cb();
});
};
const webpConvert = (cb) => {
gulp.src("./dist/img/**/*")
.pipe(gm((gmfile) => {
return gmfile.colorspace("rgb");
}))
.pipe(imagemin([
webp({
quality: 75
})
]))
.pipe(gulp.dest("./dist/webp"));
cb();
};
const imgSquash = (cb) => {
return gulp.src("./site/static/img/**/*")
.pipe(imagemin([
imagemin.gifsicle({
interlaced: true,
optimizationLevel: 3
}),
imagemin.jpegtran({
progressive: true
}),
imageminMozjpeg({
quality: 80
}),
imagemin.optipng({
optimizationLevel: 5
}),
imagemin.svgo({
plugins: [{
removeViewBox: true
},
{
cleanupIDs: false
}
]
})
]))
.pipe(gulp.dest("./dist/img"));
};
const server = (cb) => {
browserSync.init({
server: {
baseDir: "./dist"
}
});
gulp.watch("./src/js/**/*.js", js);
gulp.watch("./src/css/**/*.css", css);
gulp.watch("./site/**/*", hugo);
cb();
};
const buildSite = (cb, options) => {
const args = options ? defaultArgs.concat(options) : defaultArgs;
return cp.spawn(hugoBin, args, {
stdio: "inherit"
}).on("close", (code) => {
if (code === 0) {
browserSync.reload("notify:false");
cb();
} else {
browserSync.notify("Hugo build failed :(");
cb("Hugo build failed");
}
});
};
export {
hugo,
hugoPreview,
build,
buildPreview,
css,
js,
webpConvert,
imgSquash,
server
};
When you execute callback in your tasks, gulp thinks that task is finished. Instead of calling callback you should return stream, so that gulp knows when task is finished.
You should change your tasks in something similar like this:
const css = (cb) => {
return gulp.src("./src/css/*.css")
.pipe(postcss([
cssImport({
from: "./src/css/main.css"
}),
cssnext(),
cssnano(),
]))
.pipe(gulp.dest("./dist/css"))
.pipe(browserSync.stream());
// cb(); --comment this line
};
Add 'return' and comment line with cb();

Gulp Watch tasks finishing early

I have a gulp file that runs Sass and injects my CSS, app and Bower js files in separate tasks. I would like, at the end of the task, to watch my SCSS files and run Sass on change, and application code and inject new files (with a view to livereload when I can get this working).
Unfortunately, I've run into a problem where my watch tasks end early, therefore no changes are being watched for.
I've read in another question that the watch tasks have to be returned, however, this did not help...
Here is my gulpfile (with prod tasks removed)
const gulp = require('gulp')
// plugins
const concat = require('gulp-concat')
const uglify = require('gulp-uglify')
const rename = require('gulp-rename')
const closure = require('gulp-jsclosure')
const rev = require('gulp-rev')
const sass = require('gulp-sass')
const cssmin = require('gulp-cssmin')
const bower = require('main-bower-files')
const strip = require('gulp-strip-comments')
const inject = require('gulp-inject')
const ngannotate = require('gulp-ng-annotate')
const mainBowerFiles = require('main-bower-files')
const templateCache = require('gulp-angular-templatecache')
const minifyHtml = require('gulp-minify-html')
const path = require('path')
const babel = require('gulp-babel')
const es = require('event-stream')
// configuration variables
const config = {
dir: {
root: 'client/',
app: './Dist/',
vendor: './Dist/',
css: 'client/',
cssMin: './Dist/',
bower: 'client/wwwroot/lib',
index: './Views/Shared/_Layout.cshtml',
indexDir: './Views/Shared',
modules: 'client/app/modules'
},
filters: {
app: 'client/app.js',
appModules: 'client/app/modules/**/*.module.js',
appModuleFiles: 'client/app/modules/**/*.js',
vendors: 'client/vendors/**/*.js',
templates: 'client/app/modules/**/*.html',
client: 'client/app/css/**/*.scss'
}
}
//----------CSS---------
gulp.task('sass', () => {
return gulp.src(['client/app/css/bootstrap.scss', 'client/app/css/app.scss', 'client/app/css/themes/theme-f.scss'])
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('build/css'));
})
gulp.task('inject-css', ['sass'], () => {
var sources = gulp.src(['build/css/bootstrap.css', 'build/css/app.css', 'build/css/theme-f.css'], { read: false }, { name: 'css' });
return gulp.src(config.dir.index)
.pipe(inject(sources))
.pipe(gulp.dest(config.dir.indexDir));
})
//--------End CSS-------
//----------App---------
gulp.task('inject-js', ['inject-bower'], () => {
var sources = gulp.src([config.filters.app, config.filters.appModules, config.filters.appModuleFiles], { read: false });
return gulp.src(config.dir.index)
.pipe(inject(sources))
.pipe(gulp.dest(config.dir.indexDir));
})
//--------End App-------
//---------Vendor-------
gulp.task('inject-bower', ['inject-css'], () => {
let bower = gulp.src(mainBowerFiles(), { read: false }, { relative: true })
return gulp.src(config.dir.index)
// .pipe(inject(es.merge(bower, vendors), { name: 'vendor' }))
.pipe(inject(bower, { name: 'vendor' }))
.pipe(gulp.dest(config.dir.indexDir));
})
//-------End Vendor-----
//----------Prod--------
//---------Watches-------
gulp.task('scripts:watch', () => {
return gulp.watch([config.filters.app, config.filters.appModuleFiles], ['inject-js']);
})
gulp.task('sass:watch', () => {
return gulp.watch(config.filters.scss, ['sass']);
})
gulp.task('watch', ['scripts:watch', 'sass:watch'], () => {
console.log(" ");
console.log("Watching for changes...");
console.log(" ");
})
//-------End Watches-----
//----------Tasks--------
gulp.task('default', ['inject-js', 'inject-bower', 'inject-css',' watch'], () => {
// gulp.watch([config.filters.app, config.filters.appModuleFiles], ['inject-js'])
// gulp.watch(config.filters.scss, ['sass'])
})
As you can probably see from the commented out code, I have also tried running these watched directly inside of the default task.
This is the console output from running gulp
[12:48:12] Using gulpfile C:\source\Icon.Admin\src\UI\Icon.Admin\gulpfile.js
[12:48:12] Starting 'scripts:watch'...
[12:48:12] Finished 'scripts:watch' after 145 ms
[12:48:12] Starting 'sass:watch'...
[12:48:12] Finished 'sass:watch' after 180 μs
[12:48:12] Starting 'watch'...
Watching for changes...
[12:48:12] Finished 'watch' after 159 μs
Any help with this is greatly appreciated!
Fixed this by running my watch tasks inside of the main watch task:
gulp.task('watch', [], () => {
console.log(" ");
console.log("Watching for changes...");
console.log(" ");
gulp.watch([config.filters.app, config.filters.appModuleFiles], ['inject-js']);
gulp.watch(config.filters.client, ['sass']);
})
Well, Inside your sass:watch it refers to config.filters.scss but that is no where to be found in the config object. Probably why your scss isn't compiling.
...
gulp.task('scripts:watch', () => {
return gulp.watch([config.filters.app, config.filters.appModuleFiles], ['inject-js']);
})
gulp.task('sass:watch', () => {
return gulp.watch(config.filters.client, ['inject-sass']);
})
gulp.task('default', ['inject-js', 'inject-bower', 'inject-css', 'scripts:watch', 'sass:watch']);
This should be all you need.

An error when use gulp and babelify?

This is my gulp file
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
gulp.task('build', function () {
return browserify({entries: 'main.js', extensions: ['.js'], debug: true})
.transform(babelify)
.bundle()
.on("error", function (err) { console.log("Error : " + err.message); })
.pipe(source('bundle.js'))
.pipe(gulp.dest('dist'));
});
gulp.task('watch', ['build'], function () {
gulp.watch('main.js', ['build']);
});
gulp.task('default', ['watch']);
Here is my main.js
var React = require('react');
var ReactDOM = require('react-dom');
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
There is an error:unexcepted token (5:2) while parsing file main.js.
I have checked my code serveral times, still don't know why?
Please try to run this command below and change gulp.task() method to below.
npm i babel-preset-react
gulp.task('build', function () {
return browserify({entries: 'main.js', extensions: ['.js'], debug: true})
.transform(babelify.configure({
presets: ["react"]
}))
.bundle()
.on("error", function (err) { console.log("Error : " + err.message); })
.pipe(source('bundle.js'))
.pipe(gulp.dest('dist'));
});