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

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();
});
});

Related

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.

Browsersync stream not working

Browsersync stream is not working for me.
I've copied example from official documentation and it won't working. Reloading for html and js files working fine. Only sass streaming wouldn't work. I've read all the issues on github and can't find an answer for my question.
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence');
// Development Tasks
// -----------------
gulp.task('serve', ['sass'], function() {
browserSync.init({
server: {
baseDir: "./app",
index: 'index.html'
}
});
gulp.watch('app/styles/*.scss', ['sass']);
gulp.watch("app/*.html").on('change', browserSync.reload);
gulp.watch('app/pages/*.html').on('change', browserSync.reload);
gulp.watch('app/js/**/*.js').on('change', browserSync.reload);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return gulp.src('app/styles/*.scss'). // Gets all files ending with .scss in app/scss and children dirs
pipe(sass().on('error', sass.logError)). // Passes it through a gulp-sass, log errors to console
pipe(gulp.dest('app/css')). // Outputs it in the css folder
pipe(browserSync.stream());
})
// Build Sequences
// ---------------
gulp.task('default', function(callback) {
runSequence([
'sass', 'serve'
], callback)
})
gulp.task('build', function(callback) {
runSequence('clean:dist', 'sass', [
'useref', 'images', 'fonts'
], callback)
})
I would make three quick changes to see if they help. First
const browserSync = require("browser-sync").create();
Note the create() at the end, you need that. Second, simplify this:
gulp.task('default', function(callback) {
runSequence([
'sass', 'serve'
], callback)
})
to:
gulp.task('default', ['serve']);
Your 'serve' task calls the 'sass' task first anyway so you don't need the renSequence stuff. Finally, change:
pipe(browserSync.stream());
to:
pipe(browserSync.reload({stream:true}));
I would also make this change:
gulp.watch('app/js/**/*.js').on('change', browserSync.reload(stream:true}));

Gulp Live Reload Not Working

I am having issues trying to get LiveReload working with Gulp Connect plugin.
Below is my gulpfile.js
I have my html files in same directory as gulpfile.js and all sass files are imported into /sass/styles.scss from same folder (smacss) and other partial files in /sass/modules/*.scss
Help appreciated
var gulp = require('gulp');
var sass = require('gulp-sass');
var connect = require('gulp-connect');
gulp.task('connect', function(){
connect.server({
root: '.',
livereload: true
});
});
// keeps gulp from crashing for scss errors
gulp.task('sass', function () {
return gulp.src('./sass/*.scss')
.pipe(sass({ errLogToConsole: true }))
.pipe(gulp.dest('./css'));
});
gulp.task('livereload', function (){
gulp.src('.')
.pipe(connect.reload());
});
gulp.task('watch', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
gulp.watch('.', ['livereload']);
});
gulp.task('default', ['connect', 'watch', 'sass']);
Not sure if your root path is working here. Can you try root: './' or just root: '/' maybe ?
And the gulp.watch and gulp.src might need files path instead of directory path. Can you try gulp.src('./*') and gulp.watch('./*') maybe ?
This ended up working for me:
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var prefix = require('gulp-autoprefixer');
// POST CSS
var postcss = require('gulp-postcss');
var cssnext = require('postcss-cssnext');
var connect = require('gulp-connect');
gulp.task('myStyles', function () {
var processors = [
cssnext()
];
gulp.src('sass/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({outputStyle: 'expanded'}))
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.write('.', {
includeContent: false,
sourceRoot: '../sass'
}))
.pipe(gulp.dest('css'))
.pipe(connect.reload());
});
gulp.task('connect', function() {
connect.server({
livereload: true
});
});
gulp.task('watchMyStyles', function() {
gulp.watch('sass/*.scss', ['myStyles']);
});
gulp.task('default', ['watchMyStyles', 'connect']);
gulp.task('server', [ 'connect']);

Gulp: How to use Browsersync, Sourcemaps, Autoprefixer and CSS Cleaner together?

See below. The problem I'm having with my current code is that Sourcemaps aren't getting injected via Browsersync. Am I missing something here or doing it the wrong way?
For reference:
https://www.browsersync.io/docs/gulp/#gulp-sass-maps
// requirements
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var browserSync = require('browser-sync').create();
var prefix = require('gulp-autoprefixer');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var cssclean = require('gulp-clean-css');
// create sass tasks
gulp.task('sass', function() {
return sass('assets/scss/style.scss', {sourcemap: true, style: 'compact'})
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(rename({suffix: '.min'}))
.pipe(cssclean())
.pipe(prefix("last 2 versions", "> 1%", "ie 8", "Android 2", "Firefox ESR"))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('assets/styles'))
.pipe(browserSync.stream({match: '**/*.css'}))
});
gulp.task('serve', ['sass'], function() {
browserSync.init({
proxy: "localhost/portfolio2014",
open:false
});
gulp.watch("assets/scss/**/*.scss", ['sass']);
gulp.watch(["assets/styles/*.css", "site/**/*", "content/**/*", "assets/javascript/*.js"]).on('change', browserSync.reload);
});
// default task (just run gulp)
gulp.task('default', ['serve'] );
Do you have to use gulp-ruby-sass? The gulpfile.js below is adding sourcemaps with gulp-sass and updating the browser when saving .scss files with sourcemaps.
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var prefix = require('gulp-autoprefixer');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var cssclean = require('gulp-clean-css');
// create sass tasks
gulp.task('sass', function () {
return gulp.src('assets/scss/test.scss')
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(rename({ suffix: '.min' }))
.pipe(cssclean())
.pipe(prefix("last 2 versions", "> 1%", "ie 8", "Android 2", "Firefox ESR"))
.pipe(sourcemaps.write(''))
.pipe(gulp.dest('assets/styles'))
.pipe(browserSync.stream({ match: '**/*.css' }))
.on('error', function (err) {
console.error('Error!', err.message);
});
});
gulp.task('serve', ['sass'], function () {
browserSync.init({
proxy: "localhost/portfolio2014",
open: false
});
gulp.watch("assets/scss/**/*.scss", ['sass']);
gulp.watch(["assets/styles/*.css", "assets/javascript/*.js"]).on('change', browserSync.reload);
});
// default task (just run gulp)
gulp.task('default', ['serve']);

Gulp + Growl + Browser-sync notification

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

Resources