Gulp + Growl + Browser-sync notification - growl

I use gulp and growl. I create this gulpfile.js:
var gulp = require("gulp");
var less = require("gulp-less");
var notifier = require('node-notifier');
var notify = require("gulp-notify");
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
gulp.task('less', function() {
var trete;
console.log(trete);
gulp.src('css/main.less')
.pipe(less())
.on('error', function(err){
trete = err.message;
notifier.notify({
'title': 'My notification',
'message': trete
});
return false;
})
.pipe(notify("Всё заебись!"))
.pipe(gulp.dest('css/'))
});
gulp.task('bs-reload', function () {
browserSync.reload();
});
gulp.task('browser-sync', function() {
browserSync.init(['css/*.css', 'js/*.js'], {
server: {
baseDir: './'
}
});
});
gulp.task('watch', function() {
gulp.watch('css/**', ['less']);
gulp.run('less');
gulp.watch(['*.html'], ['bs-reload']);
});
gulp.task('default', ['less', 'browser-sync', 'watch']);
When I run gulp, growl shows two notification and browser-sync twice reload page. Maybe I do something wrong?

You run 'less' twice in the 'default' task. Its the first dependent task, will run, then it runs again in the 'watch' task because of gulp.run.
Remove gulp.run in 'watch' task.
Add 'less' as dependent task for 'watch' task instead.
You probably want to stream your styles instead of full page reload so pipe less through this at the end.
.pipe(gulp.dest(cssPath))
.pipe(browserSync.stream());
Your task do not return their streams, they will never finish due to that. Tasks should always return a stream or take in a done-callback and call that if they are async.
var gulp = require("gulp");
var less = require("gulp-less");
var notifier = require('node-notifier');
var notify = require("gulp-notify");
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
gulp.task('less', function() {
return gulp.src('css/main.less')
.pipe(less())
.on('error', function(err){
notifier.notify({
'title': 'My notification',
'message': err.message
});
return false;
})
.pipe(notify("Всё заебись!"))
.pipe(gulp.dest('css/'))
.pipe(browserSync.stream());
});
gulp.task('browser-sync', ['less'], function() {
browserSync.init({
server: {
baseDir: './'
}
});
});
gulp.task('watch', ['less'], function() {
gulp.watch('css/**', 'less');
gulp.watch('*.html').on('change', reload);
});
gulp.task('default', ['browser-sync', 'watch']);

Related

Gulp watch executes only one time

I know there are many questions with new gulp version . I had to change my gulpfile.js and now when I run it , it only executes once . I tried using return on gulp.watch function but it does nothing .
Here is my code :
'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
var runSequence = require('run-sequence');
var iconfont = require('gulp-iconfont');
var async = require('async');
var consolidate = require('gulp-consolidate');
var sassLint = require('gulp-sass-lint');
gulp.task('sass', function(){
return gulp.src('app/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('app/css'))
});
gulp.task('sass-lint', function () {
return gulp.src('app/scss/**/*.s+(a|c)ss')
.pipe(sassLint())
.pipe(sassLint.format())
.pipe(sassLint.failOnError())
});
gulp.task('watch', gulp.series('sass'), function (){
gulp.watch('app/scss/**/*.scss', gulp.series(gulp.parallel('sass' , 'sass-lint' )));
});
gulp.task('build', function (callback) {
runSequence(['sass'],
callback
)
});
gulp.task('iconfont', function(done){
var iconStream = gulp.src(['app/images/svg/*.svg'])
.pipe(iconfont({
fontName: 'icons',
}));
async.parallel([
function handleGlyphs(cb) {
iconStream.on('glyphs', function(glyphs, options) {
gulp.src('conf/_iconfont-template.scss')
.pipe(consolidate('lodash', {
glyphs: glyphs,
fontName: 'icons',
fontPath: '../fonts/',
className: 's'
}))
.pipe(gulp.dest('app/scss/utilities/'))
.on('finish', cb);
});
},
function handleFonts (cb) {
iconStream
.pipe(gulp.dest('app/fonts/'))
.on('finish', cb);
}
], done);
});
Here is what i get in a terminal :
Your problem is mainly here:
// your version
gulp.task('watch', gulp.series('sass'), function (){
// should be:
gulp.task('watch', gulp.series('sass', function (done) {
gulp.task now takes only two arguments.
Other comments:
This part of your 'watch' task is strange:
gulp.series(gulp.parallel('sass' , 'sass-lint' )));
gulp.series is doing nothing there, presumably you want :
gulp.parallel('sass' , 'sass-lint' ));
Final 'watch' task with done callback to signal async completion.
gulp.task('watch', gulp.series('sass', function (done){
gulp.watch('app/scss/**/*.scss', gulp.parallel('sass' , 'sass-lint'));
done();
}));
You don't need the run-sequence plugin anymore. You could change the 'build' task to use gulp.series instead.

Gulp WATCH does not listen to any changes in newly added .scss partial

I have a problem with gulp watch task.
To be precise, it doesn't work with .scss partials which I add. It starts to work only when I run the task again.
There's my gulpfile:
const gulp = require('gulp'),
plugins = require('gulp-load-plugins')({
lazy: true,
}),
browserSync = require('browser-sync'),
webpack = require('webpack'),
webpackStream = require('webpack-stream'),
webpackConfig = require('./webpack.config.js');
gulp.task('css', function () {
return gulp.src('src/sass/main.scss')
.pipe(plugins.plumber())
.pipe(plugins.sass({
includePaths: ['./node_modules'],
}))
.on('error', plugins.sass.logError)
.pipe(plugins.autoprefixer('last 4 versions'))
.pipe(plugins.combineMq({
beautify: false
}))
.pipe(gulp.dest('src/assets/css'))
.pipe(browserSync.stream());
});
gulp.task('js', () => {
gulp.src('src/assets/js/main.js')
.pipe(webpackStream(webpackConfig), webpack)
.pipe(gulp.dest('js'));
});
gulp.task("server", function () {
browserSync.init({
proxy: "http://wp-boilerplate.test"
});
});
gulp.task("watch", function () {
gulp.watch('src/sass/**/*.scss', ["css"]);
gulp.watch(["*.php", "src/assets/js/*.js"], browserSync.reload);
});
gulp.task("default", ["css", "server", "watch"]);
I've read some other posts about it but I haven't found working solution.
I'd appreciate if someone could help me with it.

Rendering 2 scss and output them via Gulp?

I'm new to Gulp,
this Gulp setting is already rendered 'main.scss' but I want to add 1 more scss file named 'styles.scss' into this Gulp but kinda stuck.
How can I insert this new scss ?
should I create a new task for new scss? well, I did but it seems that I'm doing it the wrong way.
how to add it in the correct way?
<pre><code>
"use strict";
var gulp = require('gulp'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
sass = require('gulp-sass'),
maps = require('gulp-sourcemaps'),
del = require('del'),
autoprefixer = require('gulp-autoprefixer'),
browserSync = require('browser-sync').create(),
htmlreplace = require('gulp-html-replace'),
cssmin = require('gulp-cssmin');
gulp.task("concatScripts", function() {
return gulp.src([
'assets/js/vendor/jquery-3.2.1.slim.min.js',
'assets/js/vendor/popper.min.js',
'assets/js/vendor/bootstrap.min.js',
'assets/js/functions.js'
])
.pipe(maps.init())
.pipe(concat('main.js'))
.pipe(maps.write('./'))
.pipe(gulp.dest('assets/js'))
.pipe(browserSync.stream());
});
gulp.task("minifyScripts", ["concatScripts"], function() {
return gulp.src("assets/js/main.js")
.pipe(uglify())
.pipe(rename('main.min.js'))
.pipe(gulp.dest('dist/assets/js'));
});
gulp.task('compileSass', function() {
return gulp.src("assets/css/main.scss")
.pipe(maps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer())
.pipe(maps.write('./'))
.pipe(gulp.dest('assets/css'))
.pipe(browserSync.stream());
});
gulp.task("minifyCss", ["compileSass"], function() {
return gulp.src("assets/css/main.css")
.pipe(cssmin())
.pipe(rename('main.min.css'))
.pipe(gulp.dest('dist/assets/css'));
});
gulp.task('watchFiles', function() {
gulp.watch('assets/css/**/*.scss', ['compileSass']);
gulp.watch('assets/js/*.js', ['concatScripts']);
})
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: "./"
}
});
});
gulp.task('clean', function() {
del(['dist', 'assets/css/main.css*', 'assets/js/main*.js*']);
});
gulp.task('renameSources', function() {
return gulp.src(['*.html', '*.php'])
.pipe(htmlreplace({
'js': 'assets/js/main.min.js',
'css': 'assets/css/main.min.css'
}))
.pipe(gulp.dest('dist/'));
});
gulp.task("build", ['minifyScripts', 'minifyCss'], function() {
return gulp.src(['*.html', '*.php', 'favicon.ico',
"assets/img/**", "assets/fonts/**"], { base: './'})
.pipe(gulp.dest('dist'));
});
gulp.task('serve', ['watchFiles'], function(){
browserSync.init({
server: "./"
});
gulp.watch("assets/css/**/*.scss", ['watchFiles']);
gulp.watch(['*.html', '*.php']).on('change', browserSync.reload);
});
gulp.task("default", ["clean", 'build'], function() {
gulp.start('renameSources');
});
</code></pre>
Any help really appreciated. Thanks
Assuming styles.scss is in the same folder as main.scss:
gulp.task('compileSass', function() {
// src changed so that all .scss files in folder are used
return gulp.src("assets/css/*.scss")
.pipe(maps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer())
.pipe(maps.write('./'))
.pipe(gulp.dest('assets/css'))
.pipe(browserSync.stream());
});
gulp.task("minifyCss", ["compileSass"], function() {
// same as above : gulp.src takes a glob of all .css files in css folder
return gulp.src("assets/css/*.css")
.pipe(cssmin())
// name each file with the suffix, rest of name will be same as before
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('dist/assets/css'));
});
gulp.task('clean', function() {
// changed css item so all .css files are deleted
del(['dist', 'assets/css/*.css*', 'assets/js/main*.js*']);
});

Gulp unexpectedly terminates, re-run works

I got problems with gulp on the command-line when running tasks with dependencies (in-sequence and parallel). This might be specific to my environment, I need help were to look or how to make it any more verbose.
What happens:
I run gulp bundle
It starts:
Starting 'build'
Starting 'unbundle'
Finished 'unbundle' after 11ms
Starting 'clean'
Then I am back on my command prompt. No error message, the exit code was even 0.
Then I run it again: gulp bundle
Starting 'build'
Starting 'unbundle'
Finished 'unbundle'
Starting 'clean'
Finished 'clean'
Starting 'build-system'
Starting 'build-html'
Starting 'build-css'
Starting 'build-style'
Starting 'build-locales'
Finished 'build-css'
Finished 'build-locales'
Finished 'build-style'
Finished 'build-html'
Finished 'build-system'
Finished 'build'
Starting 'bundle'
Finished 'bundle'
This time it worked. We I want to do gulp bundle again I have to run it twice again.
There are other tasks which involve even more dependencies where I must enter the same command 4x before it works.
Everytime exit code 0. Even with flag -LLLL I do not get anything out of it. Gulp version is 3.9.1.
I have collected all affected tasks from the different files and combined their requires.
var gulp = require('gulp');
var runSequence = require('run-sequence');
var changed = require('gulp-changed');
var plumber = require('gulp-plumber');
var sourcemaps = require('gulp-sourcemaps');
var paths = require('../paths');
var assign = Object.assign || require('object.assign');
var notify = require('gulp-notify');
var typescript = require('gulp-tsb');
var exec = require('child_process').exec;
var print = require('gulp-print');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var vinylPaths = require('vinyl-paths');
var del = require('del');
var bundler = require('aurelia-bundler');
var bundles = require('../bundles.js');
var sassOptions = {
outputStyle: 'expanded'
};
var autoPrefixerOptions = {
browsers: ['last 2 versions', '> 1%']
};
var typescriptCompiler = typescriptCompiler || null;
gulp.task('build-system', function() {
if(!typescriptCompiler) {
typescriptCompiler = typescript.create(require('../../tsconfig.json').compilerOptions);
}
return gulp.src(paths.dtsSrc.concat(paths.source))
.pipe(plumber())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(typescriptCompiler())
.pipe(sourcemaps.write('.', {includeContent: false, sourceRoot: '/src'}))
.pipe(gulp.dest(paths.output));
});
gulp.task('build-html', function() {
return gulp.src(paths.html)
.pipe(changed(paths.output, {extension: '.html'}))
.pipe(gulp.dest(paths.output));
});
gulp.task('build-css', function() {
return gulp.src(paths.css)
.pipe(changed(paths.output, {extension: '.css'}))
.pipe(sourcemaps.init())
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(sourcemaps.write())
.pipe(autoprefixer())
.pipe(gulp.dest(paths.output));
});
gulp.task('build-style', function () {
return gulp.src(paths.style)
.pipe(changed(paths.outputStyle, { extension: '.css' }))
.pipe(sourcemaps.init())
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(sourcemaps.write())
.pipe(autoprefixer())
.pipe(gulp.dest(paths.outputStyle));
});
gulp.task('build-locales', function () {
return gulp.src(paths.locales)
.pipe(changed(paths.output, { extension: '.json' }))
.pipe(gulp.dest(paths.output));
});
gulp.task('build', function(callback) {
return runSequence(
'clean',
['build-system', 'build-html', 'build-css', 'build-style', 'build-locales'],
callback
);
});
gulp.task('clean', ['unbundle'], function() {
return gulp.src([paths.output])
.pipe(vinylPaths(del));
});
var config = {
force: true,
baseURL: './wwwroot',
configPath: './wwwroot/config.js',
bundles: bundles.bundles
};
gulp.task('bundle', ['build'], function() {
return bundler.bundle(config);
});
gulp.task('unbundle', function() {
return bundler.unbundle(config);
});
Every task returns a gulp pipe, a Promise of call the callback method.
I have no idea why this happens and why calling gulp multiple times solves the problem once (and then you must call it multiple times again).
To have the question documented with its answer:
The problem was a breakage in the pipe model with the clean task.
I solved it using another approach, here simply calling del which returns a Promise (which is returned).
gulp.task('clean', ['unbundle'], function() {
return del([paths.output]);
});

can't get gulp to use browser-sync to refresh an express server and json

I'm learning react and the first thing I wanted was a development environment that could handle the reloading and refreshing for me. I'm following along with their tutorial here:
http://facebook.github.io/react/docs/tutorial.html
Now I wanted to add gulp into this setup. The server ( https://github.com/reactjs/react-tutorial/blob/master/server.js )works fine on its own but doesn't have browser-sync and all the extras that come along with gulp of course.
so what I did was change the server's port to 9000 and proxy the browser-sync in. However, the proxy doesn't seem to pass ajax calls to the server so it can write the json. I've included my gulpfile here.
var gulp = require('gulp');
var sass = require("gulp-ruby-sass");
var filter = require('gulp-filter');
var browserSync = require('browser-sync');
var sourcemaps = require('gulp-sourcemaps');
var server = require('gulp-express');
var reload = browserSync.reload;
gulp.task('server', function(){
server.run(['app.js']);
browserSync({
proxy: "localhost:9000"
});
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html").on('change', reload);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return sass('./scss', {sourcemap: true})
.pipe(browserSync.reload({stream:true}))
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(sourcemaps.write('maps', {
includeContent: false,
sourceRoot: './app/css'
}))
.pipe(gulp.dest('./app/css'));
});
gulp.task('html', function () {
browserSync.reload();
});
// Watch scss AND html files, doing different things with each.
gulp.task('default', ['server'], function () {
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html", ['html']);
});
And here's the app.js file. You can see how it's trying to handle the json.
var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use('/', express.static(path.join(__dirname, 'app')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
res.setHeader('Content-Type', 'application/json');
res.send(data);
});
});
app.post('/comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
var comments = JSON.parse(data);
comments.push(req.body);
fs.writeFile('_comments.json', JSON.stringify(comments, null, 4), function(err) {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache');
res.send(JSON.stringify(comments));
});
});
});
app.listen(9000);
console.log('Server started: http://localhost:9000/');
Other things I've tried
Before using a proxy. I tried to switch browser-sync's middleware to the express server I had. The problem I ran into is the documentation for this seems to assume I know what I'm doing with express enough to make it work (I mean, the documentation pretty much just shows a console.logged example. Pretty useless).
using middleware
var gulp = require('gulp');
var sass = require("gulp-ruby-sass");
var filter = require('gulp-filter');
var browserSync = require('browser-sync');
var sourcemaps = require('gulp-sourcemaps');
var reload = browserSync.reload;
//server shit
var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// Static Server + watching scss/html files
gulp.task('serve', ['sass'], function() {
browserSync({
server: {
baseDir: "./app",
middleware: function (req, res, next) {
app.use('./', express.static(path.join(__dirname, 'app')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('./comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
res.setHeader('Content-Type', 'application/json');
res.send(data);
});
});
app.post('./comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
var comments = JSON.parse(data);
comments.push(req.body);
fs.writeFile('_comments.json', JSON.stringify(comments, null, 4), function(err) {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache');
res.send(JSON.stringify(comments));
});
});
});
next();
}
}
});
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html").on('change', reload);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return sass('./scss', {sourcemap: true})
.pipe(browserSync.reload({stream:true}))
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(sourcemaps.write('maps', {
includeContent: false,
sourceRoot: './app/css'
}))
.pipe(gulp.dest('./app/css'));
});
gulp.task('html', function () {
browserSync.reload();
});
// Watch scss AND html files, doing different things with each.
gulp.task('default', ['serve'], function () {
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html", ['html']);
});
The answer is nodemon! nodemon will just restart the server when it sees a change. I don't have to mess with middleware or anything. Then I just proxy browser-sync.
gulp.task('browser-sync', ['sass'], function() {
browserSync({
port: 7000,
proxy: "http://localhost:5000",
files: ["app/**", "scss/**.*.scss"]
});
gulp.watch(sassFolder + '**/*.scss', ['sass']);
gulp.watch(distFolder + '**/*.html').on('change', reload);
});
gulp.task('nodemon', function (cb) {
return nodemon({
script: 'server.js',
ignore: [
'./bower_components/**',
'./node_modules/**',
'./build/**'
]
}).on('start', function () {
cb();
});
});

Resources