Browsersync not reloading browser or injecting css - node.js

I've been trying to get this straight for a few days now but haven't been able to get it working the way I need to. I'm unable to find any examples of other people using Browsersync with .net core, that may even be the reason I'm experiencing all of these issues. But I can't find any evidence that proves that and wouldn't understand why exactly that would be the case.
Anyway... I've got everything working in my gulp file exactly how I want it to for sass/js for handling errors, etc. I'm not new to gulp otherwise I'd blame my lack of experience for my inability to get this working.
Here's my gulp file followed by what the output is when running gulp.
Default Task:
const gulp = require("gulp"),
uglify = require("gulp-uglify"),
sass = require("gulp-sass"),
rename = require('gulp-rename'),
sassGlob = require('gulp-sass-glob'),
postcss = require('gulp-postcss'),
autoprefixer = require('gulp-autoprefixer'),
sourcemaps = require('gulp-sourcemaps'),
cleanCSS = require('gulp-clean-css'),
concat = require('gulp-concat'),
msbuild = require('gulp-msbuild'),
through = require('through2'),
notifier = require('node-notifier'),
browserSync = require('browser-sync').create();
// Static Server + watching scss/html files
gulp.task('serve', ['sass', 'compileJS'], function() {
browserSync.init({
proxy : {
target: "https://localhost:3000",
},
files: ['./wwwroot/css/*'],
rewriteRules: [
{
match: new RegExp('/css/main.min.css'),
fn: function() {
return './wwwroot/css/main.min.css'
}
}
]
});
//Watch for any changes to the scss files.
gulp.watch('./wwwroot/sass/**/*.scss', ['sass']);
//Watch for any changes to the js files, reload after those changes are made.
gulp.watch('./wwwroot/js/source/*.js', ['compileJS']).on('change', browserSync.reload);
//Watch for any changes to a .cshtml file and reload the browser if/when that change happens.
gulp.watch("./**/*.cshtml").on('change', browserSync.reload);
});
gulp.task('default', ['serve']);
/**
* Compiles SASS files and stores the result into the public folder
*/
gulp.task('sass', function () {
return gulp.src('./wwwroot/sass/main.scss')
.pipe(sassGlob())
.pipe(sass().on('error', function (err) {
console.log('Sass Error:', err.toString());
notifier.notify({
'title': 'Gettin\' Sassy 💁‍♀️',
'message': 'You goofed. Check your terminal window for more information.'
});
this.emit("end");
}))
.pipe(postcss([require('autoprefixer')]))
.pipe(
autoprefixer({
browsers: ['last 2 versions'],
cascade: false
})
)
.pipe(
through.obj(function(chunk, enc, cb) {
cb(null, chunk)
})
)
.pipe(cleanCSS({compatibility: 'ie8',
level: 2}))
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('./wwwroot/css'))
.pipe(browserSync.stream());
});
/**
* Compiles the Javascript files and stores the result in the public folder
*/
gulp.task('compileJS', function (done) {
return gulp.src('./wwwroot/js/source/*.js')
.pipe(sourcemaps.init())
.pipe(concat('main.js'))
.pipe(uglify().on('error', function (err) {
console.log('JS Uglify Error:', err.toString());
notifier.notify({
'title': 'JS Compile Error',
'message': 'Something about your JS is a little off. Check yourself before you wreck yourself.'
});
this.emit("end");
}))
.pipe(rename({suffix: '.min'}))
.pipe(sourcemaps.write('../maps'))
.pipe(gulp.dest('./wwwroot/js/dist'));
});
Output:
$ gulp
[21:34:15] Using gulpfile
~/Repos/PROJECT_DIRECTORY/PROJECT_NAME/gulpfile.js
[21:34:15] Starting 'sass'...
[21:34:15] Starting 'compileJS'...
[21:34:15] Finished 'sass' after 437 ms
[21:34:15] Finished 'compileJS' after 426 ms
[21:34:15] Starting 'serve'...
[21:34:16] Finished 'serve' after 1 s
[21:34:16] Starting 'default'...
[21:34:16] Finished 'default' after 68 μs
[Browsersync] Proxying: https://localhost:3000
[Browsersync] Access URLs:
------------------------------------
Local: https://localhost:3000
External: https://10.0.0.137:3000
------------------------------------
UI: http://localhost:3001
UI External: http://localhost:3001
------------------------------------
[21:34:35] Starting 'sass'...
[Browsersync] 1 file changed (main.min.css)
[21:34:35] Finished 'sass' after 207 ms
[21:34:58] Starting 'compileJS'...
[21:34:58] Finished 'compileJS' after 154 ms
[Browsersync] Reloading Browsers...
So, looking at that output you would probably think to yourself, "This dude is an idiot... Browsersync states that it's reloading browsers..." Right, it does state that, but it is not reloading the browser. Browsersync also fails to inject my css into the browser as well.
As I mentioned, I've used gulp before, and this setup closely represents the gulp files that I use when doing Wordpress development as well. However, it won't work for this project (which has led me to my .net core / Visual Studio suspicions).

You could just do something like this
Create a env variable thats global to your application then above the closing tag in your view you can add the following code.
This code is how I do it in Laravel with my Blade templates but it should be exactly the same you just need to replace it with the way .NET does it, I think they use Razor templating engine :)
{{-- Live reload with browser sync --}}
#if (!empty(env('APP_ENV')) && env('APP_ENV') === 'local')
<script
async
defer
src="{{ URL::to('/') . ':3000/browser-sync/browser-sync-client.js?v=2.26.7'}}">
</script>
#endif
Hope this helps you.
Just for interest sake below is my gulp pipeline:
const browserSync = require("browser-sync");
const sass = require("gulp-sass");
const autoprefixer = require("gulp-autoprefixer");
const sourcemaps = require("gulp-sourcemaps");
const rename = require("gulp-rename");
const reviser = require("gulp-rev");
const runSequence = require("run-sequence");
gulp.task("browserSync", function() {
return browserSync.init({
open: false,
https: false,
notify: false,
injectChanges: true,
proxy: "http://{site-name-here}.local/",
});
});
gulp.task("compile:scss", function() {
return (
gulp
// Gets the main.scss file
.src("resources/assets/scss/main.scss")
// Passes it through a gulp-sass, log errors to console
.pipe(sass().on("error", sass.logError))
// Adds versioning
.pipe(reviser())
// Add vendor prefixes
.pipe(
autoprefixer({
browsers: ["last 2 versions"],
cascade: false
})
)
// Rename the file
.pipe(rename({ suffix: ".min" }))
// Outputs it in the css folder
.pipe(gulp.dest("public/css"))
// Add sourcemaps
.pipe(sourcemaps.write())
// Adds versioned file to manifest so we can access with the same name
.pipe(reviser.manifest("manifest/rev-manifest.json"), { merge: true })
// Outputs it in the css folder
.pipe(gulp.dest("public/css"))
.pipe(
browserSync.reload({
// Reloading with Browser Sync
stream: true
})
)
);
});
// Watchers
gulp.task("watch", function() {
gulp.watch(["./resources/assets/scss/**/*"], "compile:scss", browserSync.reload);
});
// Default task
gulp.task("start", function(callback) {
return runSequence(
"browserSync",
"compile:scss",
"watch",
callback
);
});
to use it I just run gulp start
Keep in mind that running gulp like this you will need to have gulp installed globally. to do this run npm install --global gulp-cli

Related

Gulp task is causing my Node process to hang

I'm trying to run the 'rundev' task in the following gulp code but it keeps causing my Node/Gulp process to hang. I can't unhang them without restarting my computer so tracking down the problem has proven difficult.
const gulp = require("gulp");
const concat = require("gulp-concat");
const uglify = require("gulp-uglify");
const uglifycss = require("gulp-uglifycss");
const del = require("del");
const sass = require('gulp-sass');
const streamqueue = require('streamqueue');
const gzip = require('gulp-gzip');
const compression = require('compression');
const browserSync = require("browser-sync").create();
const scripts = require("./scripts");
const styles = require("./styles");
var devMode = false;
gulp.task("html", function() {
gulp.src("./src/html/**/*.html")
.pipe(gulp.dest("./dist/"))
/*.pipe(gzip({extension: 'gz'}))
.pipe(gulp.dest("./dist/"))*/
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("css", function() {
var cssRaw = gulp.src(styles["css"])
.pipe(uglifycss());
var cssFromSass = gulp.src(styles["scss"])
.pipe(sass({outputStyle: 'compressed'}));
return streamqueue({objectMode: true},
cssFromSass,
cssRaw)
.pipe(concat("allStyles.min.css"))
.pipe(gulp.dest("./dist/css"))
/*.pipe(gzip({extension: 'gz'}))
.pipe(gulp.dest("./dist/css"))*/
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("js", function() {
var jsMin = gulp.src(scripts["min"]);
var jsOther = gulp.src(scripts["other"])
.pipe(uglify());
return streamqueue({objectMode: true},
jsMin,
jsOther)
.pipe(concat("allScripts.min.js"))
.pipe(gulp.dest("./dist/js"))
/*.pipe(gzip({extension: 'gz'}))
.pipe(gulp.dest("./dist/js"))*/
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("fonts", function() {
gulp.src(["./src/fonts/**/*.eot",
"./src/fonts/**/*.svg",
"./src/fonts/**/*.ttf",
"./src/fonts/**/*.woff",
"./src/fonts/**/*.woff2"])
.pipe(gulp.dest("./dist/fonts"))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("images", function() {
gulp.src(["./src/images/**/*.*"])
.pipe(gulp.dest("./dist/images"))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("sounds", function() {
gulp.src(["./src/sounds/**/*.*"])
.pipe(gulp.dest("./dist/sounds"))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task("clean", function() {
return del('./dist/**', {read: false});
});
gulp.task("build", ['clean'], function() {
gulp.start(["css", "js", "html", "fonts", "images", "sounds"]);
});
gulp.task("browser-sync", function() {
browserSync.init(null, {
open: false,
server: {
baseDir: "dist",
middleware: compression()
}/*,
httpModule: 'http2',
https: true*/
});
});
gulp.task("rundev", function() {
devMode = true;
gulp.start(["build", "browser-sync"]);
gulp.watch(["./src/css/**/*.css", "./src/css/**/*.scss"], ["css"]);
gulp.watch(["./src/js/**/*.js"], ["js"]);
gulp.watch(["./src/html/**/*.html"], ["html"]);
gulp.watch(["./src/fonts/**/*.*"], ["fonts"]);
});
I recently picked this project back up after a month long break and haven't touched the code since, yet I've never had this issue before.
I have this problem when I try to run 'gulp rundev' in my Git Bash window. It appears to complete without errors but never actually serves the files and I can't use the Git Bash window or even close it afterwards (none of these work: clicking exit, Alt+F4, or killing the process in Task Manager). The only way to get rid of it is to restart the computer. I'm using Windows 10, Node v8.9.4, Gulp v3.9.1, Brackets, and Git Bash as my development environment in case that helps.
Here's a copy of the output:
MyName#MyComputer MINGW64 ~
$ cd Documents/GitHub/PoeFilterEditor
MyName#MyComputer MINGW64 ~/Documents/GitHub/PoeFilterEditor (Development)
$ gulp rundev
[12:11:27] Using gulpfile ~\Documents\GitHub\PoeFilterEditor\gulpfile.js
[12:11:27] Starting 'rundev'...
[12:11:27] Starting 'clean'...
[12:11:27] Starting 'browser-sync'...
[12:11:27] Finished 'browser-sync' after 114 ms
[12:11:28] Finished 'rundev' after 816 ms
[Browsersync] Access URLs:
--------------------------------------
Local: http://localhost:3000
External: http://192.168.1.142:3000
--------------------------------------
UI: http://localhost:3001
UI External: http://192.168.1.142:3001
--------------------------------------
[Browsersync] Serving files from: dist
I do remember getting more 'Starting' and 'Finished' lines in the output for the other tasks that are called by 'rundev' but otherwise the output looks normal.
Since the 'clean' task never reports as 'Finished' I assume the problem is somehow related to that and my research seems to indicate that the problem has something to do with permissions or the files being locked when it tries to operate on them. To this end, I've tried messing with the devMode, closing all programs except the Git Bash to call the task, and making sure everything is running with admin privileges, but it always hangs.
I'm a bit new to Node and Gulp so there may be something glaringly obvious that I don't even know to ask about, so hopefully someone here can help me learn my way through this.

Unable to access Browser-sync External IP on Ubuntu 16.04

I'm trying to follow along with a wordpress guide on Lynda.com that instructs me to use npm and Browser-Sync. Everything was working properly when I was working on a windows machine but I have recently setup a linux server (Ubuntu 16.04) and cannot seem to access the External URL Browser-Sync gives me. I am on the same network, and it does not work on any of my devices. I have the site setup to http://custom.local. Below is the Gulpfile.js I am using to initiate browser-sync.
var themename = 'custom';
var gulp = require('gulp'),
// Prepare and optimize code etc
autoprefixer = require('autoprefixer'),
browserSync = require('browser-sync').create(),
image = require('gulp-image'),
jshint = require('gulp-jshint'),
postcss = require('gulp-postcss'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
// Only work with new or updated files
newer = require('gulp-newer'),
// Name of working theme folder
root = '../' + themename + '/',
scss = root + 'sass/',
js = root + 'js/',
img = root + 'images/',
languages = root + 'languages/';
// CSS via Sass and Autoprefixer
gulp.task('css', function() {
return gulp.src(scss + '{style.scss,rtl.scss}')
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'expanded',
indentType: 'tab',
indentWidth: '1'
}).on('error', sass.logError))
.pipe(postcss([
autoprefixer('last 2 versions', '> 1%')
]))
.pipe(sourcemaps.write(scss + 'maps'))
.pipe(gulp.dest(root));
});
// Optimize images through gulp-image
gulp.task('images', function() {
return gulp.src(img + 'RAW/**/*.{jpg,JPG,png}')
.pipe(newer(img))
.pipe(image())
.pipe(gulp.dest(img));
});
// JavaScript
gulp.task('javascript', function() {
return gulp.src([js + '*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(gulp.dest(js));
});
// Watch everything
gulp.task('watch', function() {
gulp.task('watch', function() {
browserSync.init({
open: false,
proxy: 'custom.local',
port: 8080
});
gulp.watch([root + '**/*.css', root + '**/*.scss' ], ['css']);
gulp.watch(js + '**/*.js', ['javascript']);
gulp.watch(img + 'RAW/**/*.{jpg,JPG,png}', ['images']);
gulp.watch(root + '**/*').on('change', browserSync.reload);
});
// Default task (runs at initiation: gulp --verbose)
gulp.task('default', ['watch']);
I've tried using different ports, and setting tunnel: true, and anything else I can find, but I'm getting a whole lot of nothing. Any assistance would be amazing.
Thank you,
If you come across this and are having a similar issue, I just fixed it. I am using a headless environment so I didn't think to set up an entry in the hosts file.
/etc/hosts
127.0.0.1 custom.local

Gulp Nodemon - how do I make Nodemon exit on file change

Currently I have a very simple Gulp build script:
const gulp = require('gulp');
const ts = require('gulp-typescript');
const tsProject = ts.createProject('tsconfig.json');
const del = require('del');
const nodemon = require('gulp-nodemon');
gulp.task('build-clean', function() {
return del('dist');
});
gulp.task('build', ['build-clean'], function () {
return gulp.src('src/**/*.ts')
.pipe(tsProject())
.pipe(gulp.dest('dist'));
});
gulp.task('start', ['build'], function () {
nodemon({
script: 'dist/app.js'
, ext: 'js html'
})
})
This reloads the page on changes to JS or HTML files.
This is useful for developing, but on production I want the exact opposite. If my files change, that's because of a git push to my server. That means Jenkins will run, after that's finished Jenkins will push the code to my webfolder.
I want to stop this nodemon server if Jenkins pushes the code, because a completely fresh gulp-build will be executed, including the Nodemon server.
So - how can I make nodemon exit after files change instead of restarting?
Maybe should you just use nodein production instead of nodemon
gulp.task('start', ['build'], function () {
node({
script: 'dist/app.js'
, ext: 'js html'
})
})

browser sync reloading injecting works, but reloads after

it seems there is something im missing - Im just trying to get the css injection working on this project.
The server proxy works
The file watcher too
The injection works,
but the page always reloads half a second after...
Im on Mac osx 10.11.6 (15G1108)
Node v4.1.1
here is my gulpfile:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
var sass = require('gulp-sass');
var plumber = require('gulp-plumber');
var notify = require("gulp-notify");
var src = {
scss: 'assets/scss/**',
css: 'assets/css/',
html: 'app/*.html'
};
gulp.task('serve', ['sass'], function() {
browserSync.init({
proxy: "intouch.local",
open: false,
reloadOnRestart: false,
injectChanges: true,
});
gulp.watch(src.scss, ['sass']);
});
gulp.task('sass', function() {
var onError = function(err) {
notify.onError({
title: "Gulp",
subtitle: "Failure!",
message: "Error: <%= error.message %>",
sound: "Beep"
})(err);
this.emit('end');
};
return gulp.src(src.scss)
.pipe(plumber({errorHandler: onError}))
.pipe(sass())
.pipe(gulp.dest(src.css))
// NOTE: i've tried with all of these lines, all do the same...
// .pipe(reload({stream: true}))
// .pipe(browserSync.stream())
.pipe(browserSync.reload({
stream: true
}))
.pipe(notify({
title: 'Gulp',
subtitle: 'success',
message: 'Sass task',
sound: "Pop"
}));
});
gulp.task('default', ['serve']);
Adjust the glob for the sass files you want to compile to only match .scss (or .sass) files:
e.g. in your code example change assets/scss/** to assets/scss/**/*.scss.
A broad glob can result in unexpected files (typically source maps) being passed down the pipeline and Browsersync's default behaviour when it encounters modified files that can't be streamed is to reload the page, hence you get a successful injection for the CSS and then a hard reload for some files you probably didn't expect / don't care about.

Events gulp-nodemon are not firing

I am currently trying to write a gulp task that allows me to serve development code up through a node webserver and use browser sync to reload the page. In doing so i'm attempting to use the events with nodemon, so for example when start event occurs, I want my gulp to log what its starting. Currently the events for gulp nodemon are not firing at all. No error is being thrown and the web server is starting. I'm not sure what I am doing wrong.
gulp.task('serve-dev', ['inject'], function(){
var isDev = true;
var nodeOptions = {
script: config.nodeServer,
delayTime: 1,
env: {
'PORT': port,
'NODE_ENV': isDev ? 'dev': 'build'
},
watch: ['server.js']
};
$.nodemon(nodeOptions)
.on('start', function(){
log('*** nodemon started');
// startBroswerSync();
})
.on('restart', function (ev){
log('*** nodemon restarted');
log('files changed on restart:\n' + ev);
})
.on('crash', function(){
log('Server Crashed for some reason');
})
.on('exit', function(){
log('Server Ended Cleanly');
})
Here is my config File:
module.exports = function() {
var client = './src/';
var temp = './.tmp/';
var server = './server.js';
var config = {
// Location of index.html
index: client + 'index.html',
// Temp folder
temp: temp,
// All of the js files to load
js: [
client + '**/*.module.js',
client + '**/*.js',
'!' + client + '**/*.spec.js'
],
// Root Folder of App(Where to find index.html etc...)
client: client,
// Where to find build Sass and CSS files
css: [temp + '*css', client + 'css/*.css'],
// All Js to Vet
alljs: [
'./src/**/*.js',
'./*js'
],
// Path to Node Server
server: server,
//Sass to Compile
sass: ['src/scss/*.scss'],
// Bower and NPM Locations
bower: {
json: require('./bower.json'),
directory: './bower_components/',
ignorePath: '../..'
},
// Node Settings
defaultPort: 7203,
nodeServer: './server.js'
};
config.getWiredepDefaultOptions = function() {
var options = {
bowerJson: config.bower.json,
directory: config.bower.directory,
ignorePath: config.bower.ignorePath
};
return options;
};
return config;
};
Completely Unrelated answer, log method was not functioning properly, thus no log statements....sorry

Resources