How to fix 'Task function must be specified' in Gulp? - gulp

I'm studying GULP, and I want the page to update automatically when I modify the CSS.
const gulp = require("gulp");
const jshint = require("gulp-jshint");
const changed = require("gulp-changed");
const watch = require("gulp-watch");
const rename = require("gulp-rename");
const minifyCSS = require("gulp-uglifycss");
const sass = require("gulp-sass");
const cssImport = require("gulp-cssimport");
gulp.task("changed", function() {
return gulp
.src("src/css/*.css")
.pipe(changed("public/assets/css/"))
.pipe(cssImport())
.pipe(sass())
.pipe(minifyCSS())
.pipe(rename({ extname: ".min.css" }))
.pipe(gulp.dest("public/assets/css/"));
});
gulp.task("jshint", function() {
gulp
.src("src/css/*.css")
.pipe(jshint())
.pipe(jshint.reporter("default"));
});
gulp.task("watch", function() {
watch("src/css/*.css", ["changed"]);
});
gulp.task("default", ["jshint", "watch"]);
I'm trying to use "gulp-watch", but it's giving the error "Task function must be specified" in this code above.

The problem was that I was trying to watch the old version of GULP, not version 4.0.0.
So I changed my code to work, and it looked like this:
const gulp = require("gulp");
const rename = require("gulp-rename");
const minifyJS = require("gulp-uglify");
const minifyCSS = require("gulp-uglifycss");
const sass = require("gulp-sass");
const babel = require("gulp-babel");
const cssImport = require("gulp-cssimport");
gulp.task(
"base",
gulp.series(function() {
return gulp.src("src/templates/*.html").pipe(gulp.dest("public/"));
})
);
gulp.task(
"javascript",
gulp.series(function() {
return gulp
.src("src/js/*.js")
.pipe(babel({ presets: ["#babel/env"] }))
.pipe(minifyJS())
.pipe(rename({ extname: ".min.js" }))
.pipe(gulp.dest("public/assets/js/"));
})
);
gulp.task(
"css",
gulp.series(function() {
return gulp
.src("src/css/*.css")
.pipe(cssImport())
.pipe(sass())
.pipe(minifyCSS())
.pipe(rename({ extname: ".min.css" }))
.pipe(gulp.dest("public/assets/css/"));
})
);
gulp.task(
"watch",
gulp.series(function() {
gulp.watch("src/templates/*.html", gulp.parallel(["base"]));
gulp.watch("src/js/*.js", gulp.parallel(["javascript"]));
gulp.watch("src/css/*.css", gulp.parallel(["css"]));
})
);
gulp.task(
"default",
gulp.series(gulp.parallel("base", "javascript", "css", "watch"))
);

Related

Gulp works with tasks but not with watchers

I have this code:
var gulp = require('gulp'),
rename = require('gulp-rename'),
less = require('gulp-less'),
path = require('path'),
cleanCSS = require('gulp-clean-css'),
uglify = require('gulp-uglify');
const { watch, series, task } = require('gulp');
task('uglify', async function () {
gulp.src('assets/js/*.js')
.pipe(uglify())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('assets/public/js/'))
});
task('less', function () {
return gulp.src('assets/less/*.less')
.pipe(less({
paths: [ path.join(__dirname, 'less', 'fragments') ]
}))
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('assets/public/css/'));
});
task('default', series('uglify', 'less'));
/* task('default', function (){
watch('assets/less/*.less', series(less));
watch('assets/js/*.js', series(uglify));
return;
}); */
When I run the initial code, the first default, gulp works correctly and compresses my files successfully. However, when I change it to the one that has the watchers, it doesn't react to the changes, only this appears in the console:
16:02:09] Starting 'default'...
16:02:59] Starting ''...
Whay can I do?

Gulp is not watching

I'm working on an old project which is using Gulp.
I had to update gulp v3 to v4 and this is how it looks like:
var gulp = require('gulp')
var sass = require('gulp-sass')
var sourcemaps = require('gulp-sourcemaps')
var browserSync = require('browser-sync').create()
var uglify = require('gulp-uglify')
var concat = require('gulp-concat')
var notify = require('gulp-notify')
var series = require('stream-series') // Helps to concat js files in desired order
// BrowserSync task
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: './'
}
})
})
// Style task
gulp.task('sass', function () {
return gulp.src('./src/sass/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({
errLogToConsole: true,
outputStyle: 'compressed'
}))
.pipe(concat('style.min.css'))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./css'))
.pipe(browserSync.stream())
.pipe(notify({ message: 'Styles task complete' }))
})
// Script task
gulp.task('script', function () {
return series(
gulp.src('./src/js/vendor/**/*.js'),
gulp.src('./src/js/modules/**/*.js')
)
.pipe(concat('bundle.js'))
.pipe(uglify())
.pipe(gulp.dest('./js'))
.pipe(browserSync.stream())
.pipe(notify({ message: 'Script task complete' }))
})
// watch task
gulp.task('watch', gulp.series('sass', 'script', 'browserSync'), function () {
gulp.watch('./src/sass/**/*.scss', ['sass'])
gulp.watch('./src/js/**/*.js', ['script'])
gulp.watch('./index.html', browserSync.reload)
})
If I run gulp watch it compiles all sass and JS files and shows the page in browser correctly.
But after that it doesn't watch anymore and if I change any sass or JS files, those changes are not applied.
What is wrong with my gulp script?
I managed to fix it myself.
const gulp = require('gulp')
const sass = require('gulp-sass')
const sourcemaps = require('gulp-sourcemaps')
const browserSync = require('browser-sync').create()
const uglify = require('gulp-uglify')
const concat = require('gulp-concat')
const notify = require('gulp-notify')
const series = require('stream-series') // Helps to concat js files in desired order
// HTML task
function html () {
return gulp.src('./*.html')
.pipe(gulp.dest('./build'))
.pipe(browserSync.stream())
.pipe(notify({ message: 'HTML task complete' }))
}
// Style task
function style () {
return gulp.src('./src/sass/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({
errLogToConsole: true,
outputStyle: 'compressed'
}))
.pipe(concat('style.min.css'))
// .pipe(cssmin())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./build/css'))
.pipe(browserSync.stream())
.pipe(notify({ message: 'Styles task complete' }))
}
// Script task
function script () {
// return gulp.src('./src/js/**/*.js')
return series( // concats js files in desired order
gulp.src('./src/js/vendor/**/*.js'),
gulp.src('./src/js/modules/**/*.js')
)
.pipe(concat('bundle.js'))
.pipe(uglify())
.pipe(gulp.dest('./build/js'))
.pipe(browserSync.stream())
.pipe(notify({ message: 'Script task complete' }))
}
function watch () {
html()
style()
script()
browserSync.init({
server: {
baseDir: './build'
}
})
gulp.watch('./*.html', html).on('change', browserSync.reload)
gulp.watch('./src/sass/**/*.scss', style).on('change', browserSync.reload)
gulp.watch('./src/js/**/*.js', script).on('change', browserSync.reload)
}
exports.html = html
exports.style = style
exports.script = script
exports.watch = watch
please let me know if you have any suggestion to improve my solution.

Why is 'gulp watch' not updating?

There are probably a couple of little style issues here, but mostly this works. However, it doesn't seem to be watching changes to styles/*.scss files or new SCSS in that folder. Same thing with Javascript: scripts/*.js isn't updating on watch.
Could also stand to combine the SCSS and CSS without destroying the sourcemap, but that's not really important. Right now, just getting live updates to work would be nice.
const gulp = require('gulp')
const plumber = require('gulp-plumber')
const rename = require('gulp-rename')
const autoprefixer = require('gulp-autoprefixer')
const babel = require('gulp-babel')
const concat = require('gulp-concat')
const sass = require('gulp-sass')
const browserSync = require('browser-sync')
const clean = require('gulp-clean')
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const minifycss = require('gulp-minify-css');
const gulpfn = require('gulp-fn')
const fs = require('fs');
const util = require('gulp-util');
let config = { production: !!util.env.production }
gulp.task('clean', function () {
return gulp.src('build', {read: false})
.pipe(clean())
.pipe(gulpfn(function (file) {
if (!fs.existsSync('build')){
fs.mkdirSync('build');
}
}));
});
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./build"
}
});
});
gulp.task('bs-reload', function () {
browserSync.reload();
});
gulp.task('styles', function(){
gulp.src(['source/styles/**/*.scss'])
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(autoprefixer('last 2 versions'))
.pipe(gulp.dest('build/styles/'))
.pipe(rename({suffix: '.min'}))
.pipe(config.production ? minifyCSS() : util.noop())
.pipe(sourcemaps.write())
.pipe(gulp.dest('build/styles/'))
.pipe(browserSync.reload({stream:true}))
});
gulp.task('scripts', function(){
return gulp.src('source/scripts/**/*.js')
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(concat('main.js'))
.pipe(babel({presets: ['es2015', 'es2016']}))
.pipe(gulp.dest('build/scripts/'))
.pipe(rename({suffix: '.min'}))
.pipe(config.production ? uglify() : util.noop())
.pipe(gulp.dest('build/scripts/'))
.pipe(browserSync.reload({stream:true}))
});
gulp.task('external-scss', function(){
gulp.src(['external/font-awesome-4.7.0/scss/*.scss'])
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(autoprefixer('last 2 versions'))
.pipe(gulp.dest('build/external/font-awesome-4.7.0/css/'))
.pipe(rename({suffix: '.min'}))
.pipe(config.production ? minifyCSS() : util.noop())
.pipe(sourcemaps.write())
.pipe(gulp.dest('build/external/font-awesome-4.7.0/css/'))
.pipe(browserSync.reload({stream:true}))
});
const STATIC_STYLES = ['source/styles/**/*.css']
const STATIC_HYPERTEXT = ['source/**/*!template.html', 'source/**/*.html']
const STATIC_TEMPLATES = ['source/templates/*.template.html']
gulp.task('static-sources', function(){
gulp.src(STATIC_STYLES)
.pipe(gulp.dest('build/styles/'))
return gulp.src(STATIC_HYPERTEXT)
.pipe(gulp.dest('build/'))
});
gulp.task('default', ['browser-sync', 'styles', 'scripts', 'external-scss', 'static-sources'], function(){
gulp.src(['external/font-awesome-4.7.0/fonts/fontawesome-webfont.*']).pipe(gulp.dest('build/external/font-awesome-4.7.0/fonts'));
gulp.src( 'external/font-awesome-4.7.0/scss/*.scss', ['external-scss']);
gulp.src(['external/fccfavicons-master/*']).pipe(gulp.dest('build/external/fccfavicons-master'));
gulp.src(['node_modules/jquery/dist/*']).pipe(gulp.dest('build/external/jquery/dist'));
gulp.src(['node_modules/lodash/**/*']).pipe(gulp.dest('build/external/lodash'));
gulp.src(['node_modules/normalize.css/*.css']).pipe(gulp.dest('build/external/normalize.css'));
gulp.watch('source/styles/**/*.scss', ['styles']);
gulp.watch('source/scripts/**/*.js', ['scripts']);
let static_sources = []
static_sources.push(...STATIC_HYPERTEXT)
static_sources.push(...STATIC_STYLES)
gulp.watch(static_sources, ['static-sources']);
gulp.watch('*.html', ['bs-reload']);
});
You need to add return statements in your other tasks, besides scripts, to signal to gulp that they have all finished.

How to use vue.js with gulp?

I'm working with a small project using gulp and I want to learn about vue.js, so I want to use vue.js in this project, but I don't know how to configure vue.js in the gulpfile.js
I want to know how to configure gulpfile to use vue.js
My gulpfile.js
var env = require('minimist')(process.argv.slice(2)),
gulp = require('gulp'),
gutil = require('gulp-util'),
plumber = require('gulp-plumber'),
jade = require('gulp-jade'),
browserify = require('gulp-browserify'),
browserSync = require('browser-sync'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
gulpif = require('gulp-if'),
stylus = require('gulp-stylus'),
jeet = require('jeet'),
rupture = require('rupture'),
koutoSwiss = require('kouto-swiss'),
prefixer = require('autoprefixer-stylus'),
modRewrite = require('connect-modrewrite'),
imagemin = require('gulp-imagemin'),
karma = require('gulp-karma'),
cache = require('gulp-cache'),
rsync = require('rsyncwrapper').rsync;
// Call Jade for compile Templates
gulp.task('jade', function () {
return gulp.src('src/templates/*.jade')
.pipe(plumber())
.pipe(jade({pretty: !env.p}))
.pipe(gulp.dest('build/'));
});
gulp.task('copy', function() {
return gulp.src(['src/*.html', 'src/*.txt'])
.pipe(gulp.dest('build/'))
});
// Call Uglify and Concat JS
gulp.task('js', function () {
return gulp.src('src/js/**/*.js')
.pipe(plumber())
.pipe(concat('main.js'))
.pipe(gulpif(env.p, uglify()))
.pipe(gulp.dest('build/js'));
});
// Call Uglify and Concat JS
gulp.task('browserify', function () {
return gulp.src('src/js/main.js')
.pipe(plumber())
.pipe(browserify({debug: !env.p}))
.pipe(gulpif(env.p, uglify()))
.pipe(gulp.dest('build/js'));
});
// Call Stylus
gulp.task('stylus', function () {
gulp.src('src/styl/main.styl')
.pipe(plumber())
.pipe(stylus({
use:[koutoSwiss(), prefixer(), jeet(), rupture()],
compress: env.p,
}))
.pipe(gulp.dest('build/css'));
});
// Call Imagemin
gulp.task('imagemin', function () {
return gulp.src('src/img/**/*')
.pipe(plumber())
.pipe(cache(imagemin({optimizationLevel: 3, progressive: true, interlaced: true})))
.pipe(gulp.dest('build/img'));
});
// Call Watch
gulp.task('watch', function () {
gulp.watch('src/templates/**/*.jade', ['jade']);
gulp.watch('src/styl/**/*.styl', ['stylus']);
gulp.watch('src/js/**/*.js', [(env.fy) ? 'browserify' : 'js']);
gulp.watch('src/img/**/*.{jpg,png,gif}', ['imagemin']);
});
gulp.task('browser-sync', function () {
var files = [
'build/**/*.html',
'build/css/**/*.css',
'build/img/**/*',
'build/js/**/*.js',
];
browserSync.init(files, {
server: {
baseDir: './build/',
},
});
});
// Rsync
gulp.task('deploy', function () {
rsync({
ssh: true,
src: './build/',
dest: 'user#hostname:/path/to/www',
recursive: true,
syncDest: true,
args: ['--verbose'],
},
function (erro, stdout, stderr, cmd) {
gutil.log(stdout);
});
});
// Default task
gulp.task('default', [(env.fy) ? 'browserify' : 'js', 'jade', 'copy', 'stylus', 'imagemin', 'watch', 'browser-sync']);
// Build and Deploy
gulp.task('build', [(env.fy) ? 'browserify' : 'js', 'jade', 'copy', 'stylus', 'imagemin', 'deploy']);
Vueify is a browserify transform; gulp-browserify isn't maintained anymore but I assume that you can still add vueify as a transform once it's installed:
gulp.task('browserify', function () {
return gulp.src('src/js/main.js')
.pipe(plumber())
.pipe(browserify({
debug: !env.p,
transform: ['vueify']
}))
.pipe(gulpif(env.p, uglify()))
.pipe(gulp.dest('build/js'));
});
Check this out:
This is a package which lets you setup gulp task for vue.js.
https://www.npmjs.com/package/gulp-vueify
Using:
.pipe(babel({presets: ['es2015']}))
On a normal gulp task helped me concat and uglify my vue.js files.
If this is what you meant, then you will also need to install babel with npm and add:
var babel = require('gulp-babel');

Gulp - how to delete build directory before running other tasks

I got this Gulp file where I'm running various tasks.
I would like to delete the contents of my build directory before running any other tasks but can't work out how to do this.
I've tried lots of various ways I found when searching for a solution to this but can't get it to work.
Here is my Gulp file:
// List required plugins
var gulp = require('gulp'),
del = require('del'),
uglify = require('gulp-uglify'),
postcss = require('gulp-postcss'),
lost = require('lost'),
nano = require('gulp-cssnano'),
sourcemaps = require('gulp-sourcemaps'),
autoprefixer = require('autoprefixer'),
mqpacker = require('css-mqpacker'),
mixins = require('postcss-mixins'), // Must go before other plugins in the PostCSS task
nested = require('postcss-nested'),
vars = require('postcss-simple-vars'),
partials = require('postcss-import'),
plumber = require('gulp-plumber'),
gutil = require('gulp-util'),
imagemin = require('gulp-imagemin'),
pngquant = require('imagemin-pngquant'),
browserSync = require('browser-sync').create();
// Config - Paths and other config
var src = {
cssDir: 'src/css/**/*.css',
jsDir: 'src/js/**/*.js',
imgDir: 'src/img/*',
svgDir: 'src/img/svg/**/*.svg',
htmlDir: 'src/**/*.html',
srcDir: 'src/',
},
build = {
buildDir: 'build/',
cssDir: 'build/assets/css/',
htmlDir: 'build/**/*.html',
jsDir: 'build/assets/js/',
imgDir: 'build/assets/img/',
},
options = {
autoprefix: { browsers: ['last 2 versions'] },
imagemin: { optimizationLevel: 7, progressive: true, interlaced: true, svgoPlugins: [ {removeViewBox: false}, {cleanupIDs: false} ], use: [pngquant()] },
port: '80',
};
// Error handling function
// Thanks to https://cameronspear.com/blog/how-to-handle-gulp-watch-errors-with-plumber/
var onError = function(err) {
gutil.beep();
console.log(err);
this.emit('end');
}
// Clean task
gulp.task('clean:build', function () {
return del([
build.buildDir,
]);
});
// Copy HTML to Build
gulp.task('html', function () {
return gulp.src(src.htmlDir)
.pipe(plumber({
errorHandler: onError
}))
.pipe(gulp.dest(build.buildDir))
.pipe(browserSync.stream());
});
// BrowserSync Server + watching files for changes
gulp.task('server', function() {
browserSync.init({
server: {
baseDir: build.buildDir
},
port: options.port,
});
});
// PostCSS Task
gulp.task('css', function () {
var processors = [
partials(),
lost(),
autoprefixer({ browsers: ['last 2 version'] }),
mixins(),
nested(),
vars(),
mqpacker(), // Make sure mqpacker is last!
];
return gulp.src(src.cssDir)
.pipe(plumber({
errorHandler: onError
}))
.pipe(sourcemaps.init())
.pipe(postcss(processors))
//.pipe(nano()) - Disable minification during development
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(build.cssDir))
.pipe(browserSync.stream());
});
// JS Task
gulp.task('compressJS', function() {
return gulp.src(src.jsDir)
.pipe(plumber({
errorHandler: onError
}))
.pipe(uglify())
.pipe(gulp.dest(build.jsDir))
.pipe(browserSync.stream());
});
// Image Task
gulp.task('imagemin', function() {
return gulp.src(src.imgDir)
.pipe(plumber({
errorHandler: onError
}))
.pipe(imagemin(
options.imagemin
))
.pipe(gulp.dest(build.imgDir))
.pipe(browserSync.stream());
});
gulp.task('watch', function () {
gulp.watch(src.cssDir, ['css']);
gulp.watch(src.jsDir, ['compressJS']);
gulp.watch(src.htmlDir, ['html']);
gulp.watch(src.imgDir, ['imagemin']);
});
gulp.task('default', ['html', 'imagemin', 'compressJS', 'server', 'watch']);
How should I do to run the task clean:build before any other tasks but only run it once. Or is there a better way of cleaning out files before running a build?
Thanks!!
Have your tasks depend on your clean task:
gulp.task('html', ['clean:build'], function() { ... })
this is how i do it.
var del = require('del') ;
gulp.task('delete-build-folder', function(cb) {
return del([config.buildDir], cb);
});
gulp.task('default', ['delete-build-folder'], function() {
console.log('building.....');
gulp.start('copy-html', 'copy-html-views');
});