I am trying to configure Gulp and Browsersync to inject CSS changes without a reload. The attached Gulpfile.js is calling .pipe(browserSync.stream()) after the SASS task. We see it inject, but then calls a full reload.
/**
* Gulpfile
*/
var gulp = require('gulp');
var gutil = require('gulp-util');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var notify = require('gulp-notify');
var browserSync = require('browser-sync');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var fs = require("fs");
var exec = require('child_process').exec;
var config = require("./config");
var appDir = 'web'
/**
* If config.js exists, load that config for overriding certain values below.
*/
function loadConfig() {
if (fs.existsSync(__dirname + "/./config.js")) {
config = {};
config = require("./config");
}
return config;
}
loadConfig();
/*
* This task generates CSS from all SCSS files and compresses them down.
*/
gulp.task('sass', function () {
return gulp.src(appDir + '/anonymous/scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({
noCache: true,
outputStyle: "compressed",
lineNumbers: false,
loadPath: appDir + '/anonymous/css/*',
sourceMap: true
})).on('error', function(error) {
gutil.log(error);
this.emit('end');
})
.pipe(sourcemaps.write(appDir + '/anonymous/maps'))
.pipe(gulp.dest(appDir + '/anonymous/css'))
.pipe(browserSync.stream())
.pipe(notify({
title: "SASS Compiled",
message: "All SASS files have been recompiled to CSS.",
onLast: true
}))
;
});
/**
* Define a task to spawn Browser Sync.
* Options are defaulted, but can be overridden within your config.js file.
*/
gulp.task('browser-sync', function() {
browserSync.init({
port: config.browserSync.port,
proxy: config.browserSync.hostname,
open: config.browserSync.openAutomatically,
injectChanges: config.browserSync.injectChanges
});
});
/**
* Defines the watcher task.
*/
gulp.task('watch', function() {
// watch scss for changes
gulp.watch([
appDir + '/anonymous/scss/**/*.scss',
appDir + '/secure/components/**/*.scss'
], ['sass']);
});
gulp.task('default', [
'sass',
'watch',
'browser-sync'
]);
Here is the config.js that is referenced in the browsersync config.
module.exports = {
browserSync: {
hostname: "http://192.168.50.4:9080/site/secure",
port: 3000,
openAutomatically: true,
reloadDelay: 50,
injectChanges: true,
},
};
I figured out the answer to my own question.
There is a source map being generated and browsersync is watching the sourcemap folder and triggering a full refresh when the sourcemap is regenerated. Removing these lines stops the full refresh on the SASS task.
.pipe(sourcemaps.init())
.pipe(sourcemaps.write(appDir + '/anonymous/maps'))
Reference
https://github.com/BrowserSync/browser-sync/issues/235
Related
It takes far too long usually. On my laptop it literally never finishes. The PHP watch is supposed to be checking for PHP saves in the root and in any sub-directories. I'm not sure if I have the glob correct there, and maybe that's what's causing the problem?
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var mmq = require('gulp-merge-media-queries');
var phpConnect = require('gulp-connect-php');
var autoPrefixer = require('gulp-autoprefixer');
gulp.task('sass', function() {
return gulp.src('assets/css/**/*.scss')
.pipe(sass()) // Converts Sass to CSS with gulp-sass
.pipe(autoPrefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(gulp.dest('assets/css'));
});
gulp.task('connect-sync', function() {
phpConnect.server({}, function (){
browserSync({
proxy: '127.0.0.1:8000'
});
});
});
gulp.task('mmq', ['sass'], function () {
gulp.src('assets/css/styles.css')
.pipe(mmq({
log: true
}))
.pipe(gulp.dest('assets/css'))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task('watch', ['connect-sync', 'sass', 'mmq'], function(){
gulp.watch('assets/css/**/*.scss', ['sass', 'mmq']);
gulp.watch('/**/*.php', browserSync.reload);
gulp.watch('assets/js/**/*.js', browserSync.reload);
// Other watchers
});
Could be that gulp checks your node_modules folder? This is known to slow gulptasks down.
Try running each gulp statement from the console, i.e. First try gulp sass, then gulp connect.
Can you post the output from your console plz?
I want to be able to send the browserSync external URL as a parameter for an external node script in my gulp file. How can I get at that external URL through the browserSync object (or some other way)?
var gulp = require('gulp');
var shell = require('gulp-shell');
var browserSync = require('browser-sync').create();
gulp.task('default', ['browser-sync', 'config']);
gulp.task('browser-sync', function() {
browserSync.init({
proxy: "localhost:8024",
open: "external"
});
});
gulp.task('config', shell.task([
"node scripts/someNodeScript.js browserSync.externalURL"
]));
UPDATE
Based on the excellent answer by #sven-shoenung below, I slightly tweaked his solution and am successfully using this:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var spawn = require('child_process').spawn;
var externalUrl;
var browserSyncDone = function () {
spawn('node', ['scripts/someNodeScript.js', externalUrl], {stdio:'inherit'});
};
gulp.task('default', ['browser-sync']);
gulp.task('browser-sync', function() {
browserSync.init({
proxy: "localhost:8024",
open: "external"
}, function() {
externalUrl = browserSync.getOption('urls').get('external');
browserSyncDone();
});
});
You can use browserSync.getOptions('urls') to get a Map of all access URLs. It returns something like this:
Map {
"local": "http://localhost:3000",
"external": "http://192.168.0.125:3000",
"ui": "http://localhost:3001",
"ui-external": "http://192.168.0.125:3001"
}
Note that is only available after browser-sync is successfully initialized, so you need to pass a callback function to browserSync.init() or you'll try to get the value too soon.
You won't be able to use gulp-shell for the same reason. shell.task() will be set up before browser-sync has initialized, so browserSync.getOptions('urls') isn't available yet.
I recommend you use the standard nodejs child_process.spawn() instead.
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var spawn = require('child_process').spawn;
var externalUrl;
gulp.task('default', ['browser-sync', 'config']);
gulp.task('browser-sync', function(done) {
browserSync.init({
proxy: "localhost:8024",
open: "external"
}, function() {
externalUrl = browserSync.getOption('urls').get('external');
done();
});
});
gulp.task('config', ['browser-sync'], function(done) {
spawn('node', ['scripts/someNodeScript.js', externalUrl], {stdio:'inherit'}).on('close', done);
});
I need help adding source map to SASS compiler in the same CSS output folder. Till now, I got to install gulp-sourcemaps module within gulpfile.js but couldn't know success to bind sourcemaps.write as gulp.task.
Any help is much appreciated :)
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var bs = require('browser-sync').create();
gulp.task('browser-sync', ['sass'], function() {
bs.init({
server: {
baseDir: "./"
},
proxy: {
target: "localhost:8080", // can be [virtual host, sub-directory, localhost with port]
ws: true // enables websockets
}
});
});
gulp.task('sass', function() {
return gulp.src('scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('assets/css'))
.pipe(bs.reload({
stream: true
}));
});
gulp.task('watch', ['browser-sync'], function () {
gulp.watch("scss/*.scss", ['sass']);
gulp.watch("*.php").on('change', bs.reload);
});
Try this code for gulp task 'sass':
gulp.task('sass', function() {
return gulp.src('scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('assets/css'))
.pipe(bs.reload({
stream: true
}));
});
First init sourcemaps then compile sass() after that write sourcemap in the same folder ('.')
Regards
I'm using this task since 5 months everyday and works fine,
const gulp = require('gulp'),
autoprefixer = require('gulp-autoprefixer'),
plumber = require('gulp-plumber'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps');
var sassSourcePath = 'YourPath/scss/**/*.scss',
cssDestPath = 'YourPath/css/';
gulp.task('sass', () => {
return gulp
.src(sassSourcePath)
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(sourcemaps.write({includeContent: false}))
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(autoprefixer({ browser: ['last 2 version', '> 5%'] }))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(cssDestPath));
});
Also recommend you the require('gulp-csso') for the production version
A complete solution for gulp-sass, map, count all files, minify:
./sass/partial_folders/index.scss
#import 'base/_reset';
#import 'helpers/_variables';
#import 'helpers/_mixins';
#import 'helpers/_functions';
#import 'base/_typography';
etc..
./gulpfile.js
var gulp = require('gulp');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var uglifycss = require('gulp-uglifycss');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('styles', function(){
return gulp
.src('sass/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(concat('styles.css'))
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./build/css/'));
});
gulp.task('default', function(){
gulp.watch('sass/**/*.scss', ['styles']);
})
i had setup some gulp tasks and started gulp but gulp is running on port 3000 and my app config is to listen on port 4545 so it opens 3000 port but no any contents it displays output like Cannot GET /.
my project stucture is like
controllers
views
public
app.js
gulpfile.js
so i want gulp to listen on port defined in app.js and watch changes on public flder.
I have included gulp plugin like gulp-plumber,gulp-browser-sync
and its my gulpfile.js
var gulp = require('gulp'),
browserSync = require('browser-sync'),
reload = browserSync.reload,
plumber = require('gulp-plumber')
gulp.task('scripts', function() {
return gulp.src('public/javascripts/**/*.js')
.pipe(plumber())
.pipe(reload({
stream: true
}));
});
gulp.task('styles', function() {
gulp.src('public/stylesheets/**/*.css')
.pipe(plumber())
.pipe(reload({
stream: true
}));
});
// gulp.task('html', function() {
// gulp.src('app/**/*.html')
// .pipe(reload({
// stream: true
// }));
// });
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
gulp.task('watch', function() {
gulp.watch('public/javascripts/**/*.js', ['styles']);
gulp.watch('public/stylesheets/**/*.css', ['scripts']);
});
gulp.task('default', ['scripts', 'styles', 'browser-sync', 'watch']);
You can use gulp-nodemon
var gulp = require('gulp'),
nodemon = require('gulp-nodemon')
gulp.task('develop', function () {
nodemon({
script: 'app.js',
ext: 'js',
}).on('restart', function () {
// a server restarted hook can be added here
});
});
gulp.task('default', ['develop']);
Basically it will restart automatically the server when you change a js file
I run the same gulpfile on local and remote. On local, everything is fine but when on remote, both "vendors" and "assets" tasks are not doing anything and there's no error when I run the gulp. Below is my gulp script -
var gulp = require('gulp'),
gutil = require('gulp-util'),
clean = require('gulp-clean'),
changed = require('gulp-changed'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
less = require('gulp-less'),
csso = require('gulp-csso'),
jade = require('gulp-jade'),
es = require('event-stream'),
embedlr = require('gulp-embedlr'),
refresh = require('gulp-livereload'),
express = require('express'),
http = require('http'),
lr = require('tiny-lr')();
gulp.task('clean', function () {
// Clear the destination folder
gulp.src('dist/**/*.*', { read: false })
.pipe(clean({ force: true }));
});
// Vendor Files
// var vendors = {
// js: [ './bower_components/**/ZeroClipBoard.js'],
// assets: ['./bower_components/**/ZeroClipBoard.swf']
// };
// Compile JS
gulp.task('scripts', function () {
return es.concat(
// Detect errors and potential problems in your JavaScript code
// You can enable or disable default JSHint options in the .jshintrc file
// Concatenate, minify and copy all JavaScript (except vendor scripts)
gulp.src(['./src/js/**/*.js'])
.pipe(concat('main.js'))
.pipe(uglify({mangle: false}))
.pipe(gulp.dest('./dist/js'))
.pipe(refresh(lr))
)});
// Copy Vendor Script and Assets
gulp.task('assets', function () {
return gulp.src(['./bower_components/**/ZeroClipBoard.swf'], {base: './'})
.pipe(gulp.dest('./dist/vendors'));
});
gulp.task('vendors', function () {
return gulp.src(['./bower_components/**/ZeroClipBoard.js'])
.pipe(concat('vendor.js'))
.pipe(uglify({mangle: false}))
.pipe(gulp.dest('./dist/js'));
});
// Compile LESS files
gulp.task('styles', function () {
return gulp.src('./src/less/styles.less')
.pipe(less())
.pipe(rename('styles.css'))
.pipe(csso())
.pipe(gulp.dest('./dist/css'))
.pipe(refresh(lr));
});
gulp.task('templates', function () {
// Compile Jade files
return gulp.src('./src/jade/index.jade')
.pipe(jade())
.pipe(rename('index.html'))
.pipe(gulp.dest('./dist/'))
.pipe(refresh(lr));
});
gulp.task('server', function () {
// Create a HTTP server for static files
var port = 3000;
var app = express();
var server = http.createServer(app);
app.use(express.static(__dirname + '/dist'));
server.on('listening', function () {
gutil.log('Listening on http://localhost:' + server.address().port);
});
server.on('error', function (err) {
if (err.code === 'EADDRINUSE') {
gutil.log('Address in use, retrying...');
setTimeout(function () {
server.listen(port);
}, 1000);
}
});
server.listen(port);
});
gulp.task('lr-server', function () {
// Create a LiveReload server
lr.listen(35729, function (err) {
if (err) {
gutil.log(err);
}
});
});
gulp.task('watch', function () {
// Watch .less files and run tasks if they change
gulp.watch('./src/less/**/*.less', ['styles']);
// Watch .jade files and run tasks if they change
gulp.watch('./src/jade/index.jade', ['templates']);
// Watch .js files
gulp.watch('./src/js/**/*.js', ['scripts']);
});
// The dist task (used to store all files that will go to the server)
gulp.task('dist', ['clean', 'styles', 'templates', 'scripts', 'vendors']);
// The default task (called when you run `gulp`)
gulp.task('default', ['clean', 'styles', 'templates', 'scripts', 'assets', 'vendors', 'lr-server', 'server', 'watch']);