Show success message when gulp task is completed - gulp

I created a simple Gulp task to check for changes in my ES6 files. I would like to transpile them and show an error message when something went wrong.
The error screen is being displayed. However, I would like to show a different message when everything is successful. I tried the .on('end') method but this method will also be called when there are some errors.
My current Gulpfile looks like this:
const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
const pump = require('pump');
const imagemin = require('gulp-imagemin');
const sass = require('gulp-sass');
const DISTRIBUTION_PATH = 'public/theme/js/app';
const plumber = require('gulp-plumber');
const gutil = require('gulp-util');
const clear = require('clear');
gulp.task('transpile', () =>
gulp.watch('theme/js/**/*.js', () => {
return gulp.src('theme/js/**/*.js')
.pipe(plumber())
.pipe(babel({
presets: ['es2015'],
plugins: [
'transform-object-rest-spread'
]
}))
.on('error', err => {
clear();
gutil.log(gutil.colors.red('[Compilation Error]'));
gutil.log(err.fileName + ( err.loc ? `( ${err.loc.line}, ${err.loc.column} ): ` : ': '));
gutil.log(gutil.colors.red('error Babel: ' + err.message + '\n'));
gutil.log(err.codeFrame);
})
.pipe(gulp.dest(DISTRIBUTION_PATH));
})
);
Any ideas how to achieve this?

Answer might be a bit late, but for the Googler like myself I've created a solution. I've added a boolean isSuccess to determine whether the transpilation was successful. If there is an error isSuccess becomes false and the message is not shown "on end."
const gulp = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
const pump = require('pump');
const imagemin = require('gulp-imagemin');
const sass = require('gulp-sass');
const DISTRIBUTION_PATH = 'public/theme/js/app';
const plumber = require('gulp-plumber');
const gutil = require('gulp-util');
const clear = require('clear');
gulp.task('transpile', () =>
gulp.watch('theme/js/**/*.js', () => {
let isSuccess = true;
return gulp.src('theme/js/**/*.js')
.pipe(plumber())
.pipe(babel({
presets: ['es2015'],
plugins: [
'transform-object-rest-spread'
]
}))
.on('error', err => {
isSuccess = false;
clear();
gutil.log(gutil.colors.red('[Compilation Error]'));
gutil.log(err.fileName + ( err.loc ? `( ${err.loc.line}, ${err.loc.column} ): ` : ': '));
gutil.log(gutil.colors.red('error Babel: ' + err.message + '\n'));
gutil.log(err.codeFrame);
})
.pipe(gulp.dest(DISTRIBUTION_PATH))
.on('end', ()=> {
if( isSuccess )
console.log('Yay success!');
});
})
);

You can do
.on('error', () => {
// some log or code for failure
})
.on('end', () => {
// some log or code for success
});

Related

SCSS to Style.css

Long story story, the main developer that worked on this is no longer with the company and I have to take over the project that they built out - So all help would be appreciated with this.
I'm not too familiar with WordPress nor SCSS/Foundation so this will be a learning process. I need to make a css change and deploy it, but it's not showing the changes on my local environment at all.
Here is the knowledge that I have:
- Foundation was used to build this
- SCSS is being converted to Style.css
- https://cdn.site.pl/wp-content/themes/sites/style.css?ver=4.9.10 - There is a version being applied to the end of style.css
Here are the tasks that are in my gulpfile.js:
Here is his documentation:
The default gulp task runs both gulp scripts and gulp styles. To run
this task, navigate in Terminal to the project's htdocs directory, and
type:
gulp
I get this in response:
[14:00:37] Task never defined: default
[14:00:37] To list available tasks, try running: gulp --tasks
Below, I will be providing the whole gulpfile.js file
const argv = require('yargs').argv;
const {
src,
dest,
parallel,
series,
watch
} = require('gulp');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const concat = require('gulp-concat');
const postcss = require('gulp-postcss');
const cssnano = require('cssnano');
const rename = require('gulp-rename');
const uglify = require('gulp-uglify');
// Usage in gulp: gulp task-name --theme=theme-name
// Default value is 'f-sites'
const themeName = argv.theme ? argv.theme : 'f-sites';
// GULP CONFIG
const config = {
themeName: themeName,
themeDirectory: `wp-content/themes/${themeName}`
};
// GULP TASKS
// SCSS/CSS TASKS
//==================================================
function sassToCss() {
const nodeModulesSassPaths = [
'node_modules/foundation-sites/scss',
'node_modules/slick-carousel/slick',
'node_modules/jquery-fancybox/source/scss',
'node_modules/font-awesome/scss'
];
const srcPaths = [
`${config.themeDirectory}/scss/theme.scss`,
`${config.themeDirectory}/scss/theme-rtl.scss`
];
return src(srcPaths, { sourcemaps: true })
.pipe(sass({ includePaths: nodeModulesSassPaths }).on('error', sass.logError))
.pipe(autoprefixer({ browsers: ['last 2 versions', 'ie >= 10'] }))
.pipe(dest(`${config.themeDirectory}/css`, { sourcemaps: true }));
}
function cssConcatLTR() {
const srcFiles = [
`${config.themeDirectory}/css/wordpress.css`,
'./node_modules/animate.css/animate.css',
`${config.themeDirectory}/css/theme.css`,
];
return src(srcFiles, { sourcemaps: true })
.pipe(concat('project.css'))
.pipe(dest(`${config.themeDirectory}/css`, { sourcemaps: true }));
}
function cssConcatRTL() {
const srcFiles = [
config.themeDirectory + '/css/wordpress.css',
'./node_modules/animate.css/animate.css',
config.themeDirectory + '/css/theme-rtl.css'
];
return src(srcFiles, { sourcemaps: true })
.pipe(concat('project-rtl.css'))
.pipe(dest(`${config.themeDirectory}/css`, { sourcemaps: true }));
}
function cssMinifyLTR() {
const plugins = [cssnano()];
return src(`${config.themeDirectory}/css/project.css`)
.pipe(postcss(plugins))
.pipe(rename('style.css'))
.pipe(dest(config.themeDirectory));
}
function cssMinifyRTL() {
const plugins = [cssnano()];
return src(`${config.themeDirectory}/css/project-rtl.css`)
.pipe(postcss(plugins))
.pipe(rename('style-rtl.css'))
.pipe(dest(config.themeDirectory));
}
exports.default = parallel(
series(
sassToCss,
parallel(cssConcatLTR, cssConcatRTL),
parallel(cssMinifyLTR, cssMinifyRTL)
),
series(jsConcat, jsMinify)
);
exports.styles = series(
sassToCss,
parallel(cssConcatLTR, cssConcatRTL),
parallel(cssMinifyLTR, cssMinifyRTL)
);
exports.scripts = series(jsConcat, jsMinify);
This may be caused by the version of gulp-cli, you can try to upgrade it.
Relevant issues:
https://github.com/gulpjs/gulp-cli/issues/191
https://github.com/gulpjs/gulp/issues/1634

How to fix 'Task function must be specified' in 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"))
);

Using stream-combiner2 with Gulp 4

I'm trying to use stream-combiner2 with my Gulp 4 task, as advised in the current version of this recipe. However, I always receive:
The following tasks did not complete: build:js
Did you forget to signal async completion?
I've read the excellent information in this answer about Gulp 4 async completion, but I'm having trouble applying that in my task. Here's what I have:
const browserify = require('browserify')
const buffer = require('vinyl-buffer')
const combiner = require('stream-combiner2')
const gulp = require('gulp')
const jsDest = 'static/js'
const jsPath = 'build/js'
const jsSrc = `${jsPath}/**/*.js`
const source = require('vinyl-source-stream')
const sourcemaps = require('gulp-sourcemaps')
const uglify = require('gulp-uglify')
gulp.task('build:js', function () {
const combined = combiner.obj([
browserify({
entries: `${jsPath}/main.js`,
debug: true
}),
source(`${jsPath}/main.js`),
buffer(),
sourcemaps.init({ loadMaps: true }),
uglify(),
sourcemaps.write('./'),
gulp.dest(jsDest)
])
combined.on('error', console.error.bind(console))
return combined
})
Somehow I missed this fantastic recipe for browserify with multiple sources and destinations. It allowed me to finally get what I was after, including well-formed error handling:
const browserify = require('browserify')
const buffer = require('gulp-buffer')
const combiner = require('stream-combiner2')
const gulp = require('gulp')
const gutil = require('gulp-util')
const jsDest = 'static/js'
const jsSrc = 'build/js/*.js'
const sourcemaps = require('gulp-sourcemaps')
const tap = require('gulp-tap')
const uglify = require('gulp-uglify')
gulp.task('build:js', function () {
const combined = combiner.obj([
gulp.src(jsSrc, { read: false }),
tap(function (file) {
gutil.log('bundling ' + file.path)
file.contents = browserify(file.path, { debug: true }).bundle()
}),
buffer(),
sourcemaps.init({ loadMaps: true }),
uglify(),
sourcemaps.write('./'),
gulp.dest(jsDest)
])
combined.on('error', console.error.bind(console))
return combined
})
After a few hours of hacking away at it, I got fed up with the task not doing what I want at all (see comments to the post) and resorted to the deprecated gulp-browserify. Here's the solution with that plugin, but I'm completely willing to accept an answer that can correctly incorporate stream-combiner2 with browserify itself, because that'd be much better.
const combiner = require('stream-combiner2')
const gulp = require('gulp')
const jsDest = 'static/js'
const jsSrc = 'build/js/*.js'
const sourcemaps = require('gulp-sourcemaps')
const uglify = require('gulp-uglify')
gulp.task('build:js', function () {
const combined = combiner.obj([
gulp.src(jsSrc),
sourcemaps.init(),
browserify(),
uglify(),
sourcemaps.write('.'),
gulp.dest(jsDest)
])
combined.on('error', console.error.bind(console))
return combined
})

node-hbsfy not compiling templates with Gulp

I'm simply trying to compile hbs templates via Browserify and Gulp, but the compilation process fails as soon as any HTML markup is encountered from my hbs file.
I've confirmed this by removing the HTML code within the hbs file, at which point Browserify runs as expected.
Here is a simplified version of my Gulp task:
const _gulp = require('gulp');
const _browserify = require('browserify');
const _remapify = require('remapify');
const _hbsfy = require('hbsfy');
const _vinylSourceStream = require('vinyl-source-stream');
const _vinylBuffer = require('vinyl-buffer');
_gulp.task('js:dev', () => {
return _browserify({entries: './src/js/app.js', debug: true})
.plugin(_remapify, [
{
src: '**/*.hbs', // glob for the files to remap
cwd: './src/markup/components',
expose: 'components' // this will expose './src/markup/components' as 'components'
}
])
.transform(_hbsfy)
.bundle()
.pipe(_vinylSourceStream('app.js'))
.pipe(_vinylBuffer())
.pipe(_gulp.dest('dist'))
});
The hbs template:
<div class="menu"> </div>
The main JS file:
(function (){
const _handlebars = require('hbsfy/runtime');
function init () {
_handlebars.registerPartial('menu', require('components/menu.hbs'));
}
document.addEventListener('DOMContentLoaded', init);
})();
What could be going wrong? It's as if the hbsfy transform isn't running properly...
It seems this issue is actually caused by the remapify plugin. Compilation works as expected using pathmodify instead.
Here is my updated Gulp file:
const _gulp = require('gulp');
const _browserify = require('browserify');
const _pathmodify = require('pathmodify');
const _hbsfy = require('hbsfy');
const _vinylSourceStream = require('vinyl-source-stream');
const _vinylBuffer = require('vinyl-buffer');
_gulp.task('js:dev', () => {
return _browserify({entries: './src/js/app.js', debug: true})
.plugin(_pathmodify, {
mods: [
_pathmodify.mod.dir('components', process.cwd() + '/src/markup/partials/components')
]
})
.transform(_hbsfy)
.bundle()
.pipe(_vinylSourceStream('app.js'))
.pipe(_vinylBuffer())
.pipe(_gulp.dest('dist'))
});

Gulp using gulp-jade with gulp-data

I'm trying to use gulp-data with gulp-jade in my workflow but I'm getting an error related to the gulp-data plugin.
Here is my gulpfile.js
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
browserSync = require('browser-sync'),
jade = require('gulp-jade'),
data = require('gulp-data'),
path = require('path'),
sass = require('gulp-ruby-sass'),
prefix = require('gulp-autoprefixer'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
process = require('child_process');
gulp.task('default', ['browser-sync', 'watch']);
// Watch task
gulp.task('watch', function() {
gulp.watch('*.jade', ['jade']);
gulp.watch('public/css/**/*.scss', ['sass']);
gulp.watch('public/js/*.js', ['js']);
});
var getJsonData = function(file, cb) {
var jsonPath = './data/' + path.basename(file.path) + '.json';
cb(require(jsonPath))
};
// Jade task
gulp.task('jade', function() {
return gulp.src('*.jade')
.pipe(plumber())
.pipe(data(getJsonData))
.pipe(jade({
pretty: true
}))
.pipe(gulp.dest('Build/'))
.pipe(browserSync.reload({stream:true}));
});
...
// Browser-sync task
gulp.task('browser-sync', ['jade', 'sass', 'js'], function() {
return browserSync.init(null, {
server: {
baseDir: 'Build'
}
});
});
And this is a basic json file, named index.jade.json
{
"title": "This is my website"
}
The error I get is:
Error in plugin 'gulp-data'
[object Object]
You are getting error because in getJsonData you pass required data as first argument to the callback. That is reserved for possible errors.
In your case the callback isn't needed. Looking at gulp-data usage example this should work:
.pipe(data(function(file) {
return require('./data/' + path.basename(file.path) + '.json');
}))
Full example:
var gulp = require('gulp');
var jade = require('gulp-jade');
var data = require('gulp-data');
var path = require('path');
var fs = require('fs');
gulp.task('jade', function() {
return gulp.src('*.jade')
.pipe(data(function(file) {
return require('./data/' + path.basename(file.path) + '.json');
}))
.pipe(jade({ pretty: true }))
.pipe(gulp.dest('build/'));
});
Use this if you're running the task on gulp.watch:
.pipe(data(function(file) {
return JSON.parse(fs.readFileSync('./data/' + path.basename(file.path) + '.json'));
}))