Skip to content

Instantly share code, notes, and snippets.

@dennib
Last active April 8, 2021 19:43
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dennib/6f1f9aa9b59596710f62c1ef22a655f4 to your computer and use it in GitHub Desktop.
Save dennib/6f1f9aa9b59596710f62c1ef22a655f4 to your computer and use it in GitHub Desktop.
Gulp 4: ExpressJs + BrowserSync + Nodemon + Sass Watching
const gulp = require('gulp');
const sass = require('gulp-sass');
const browserSync = require('browser-sync');
const nodemon = require('gulp-nodemon');
sass.compiler = require('node-sass');
// Sass compilation
gulp.task('sass', function() {
return gulp
.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
// Sass watching, depending on "sass" task
gulp.task('sass:watch', function() {
gulp.watch('./sass/**/*.scss', gulp.series('sass'));
});
// Nodemon task:
// Start nodemon once and execute callback (browser-sync)
gulp.task('nodemon', cb => {
let started = false;
return nodemon({
script: 'server.js'
}).on('start', () => {
if (!started) {
cb();
started = true;
}
});
});
// BrowserSync task:
// calls nodemon tasks and pass itself as callback
gulp.task(
'browser-sync',
gulp.series('nodemon', () => {
browserSync.init(null, {
proxy: 'http://localhost:3000',
files: ['public/**/*.*'],
port: 5000
});
})
);
// Dev Task:
// Parallel execution of browser-sync/nodemon
// and sass watching
gulp.task('default', gulp.parallel('browser-sync', 'sass:watch'));
const express = require('express');
const app = express();
app.use(express.static('public'));
app.get('/', function(req, res) {
res.send('Hello World!');
});
// Server Listening
app.listen(3000, function() {
console.log('App listening on port 3000!');
});
@dennib
Copy link
Author

dennib commented Oct 1, 2019

Hi DevKitu, i'm sorry for this very late reply! Have you found the solution you're looking for?
In the meantime I'll try to answer what I can:

  1. Strange that sass file aren't reloading, gulp watch should recompile every .scss file present in sass folder into css folder at every change (can you post the script section of your package json?)

  2. It should always open on port 5000 if using nodemon/browsersync (server started with gulp command): your express/nodejs website si running on port 3000 and "forwards" (proxy) every call to port 5000 where browsersync is running (so that you can have live reload and all of browsersync functionalities).

  3. If I remember correctly the public folder is the static folder of the website, I made this test using handlebars templates (instead of ejs ones) but still in the views folder, so it should be fine for you too.

Please let me know how are you starting your nodejs server (with what script), maybe this gist is lacking some parts on my end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment