question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Browsersync not reloading or injecting css changes

See original GitHub issue

Issue details

I’m having trouble getting Browsersync to reload the browser or inject any css changes. I’ve used Browsersync before on numerous Wordpress projects, but never in a .net core project via Visual Studio.

My project runs on localhost:3000, which has never been an issue before (even when doing wp development), but for some reason, this is just different and I can’t figure out if I’m missing something or if I have misconfigured something, but everything seems to be there.

Terminal window 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...

Steps to reproduce/test case

Just running gulp in the terminal window to start the process is what triggers the issue.

Please specify which version of Browsersync, node and npm you’re running

  • Browsersync [ 2.26.3 ]
  • Node [ 8.12.0 ]
  • Npm [ 6.4.1 ]

Affected platforms

  • linux
  • windows
  • OS X
  • freebsd
  • solaris
  • other (please specify which)

Browsersync use-case

  • API
  • Gulp
  • Grunt
  • CLI

for all other use-cases, (gulp, grunt etc), please show us exactly how you’re using Browsersync

Gulpfile.js:

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.
        gulp.watch('./wwwroot/js/source/*.js', ['compileJS']).on('change', browserSync.reload);

        //Watch for any changes to a .cshtml file and reloads 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'));
    });

Issue Analytics

  • State:open
  • Created 5 years ago
  • Comments:6

github_iconTop GitHub Comments

2reactions
QuintonCcommented, Nov 29, 2018

So I’ve changed my watch to the following:

//Watch for any changes to the js files.
gulp.watch('./wwwroot/js/source/*.js', ['js-watch']);

Added this task:

/**
 *  Defining function for watching Javascript files. This will reload the browser when complete.
 */
gulp.task('js-watch', ['compileJS'], function (done) {
    browserSync.reload();
    done();
});

And still nothing. I get the “Reloading Browsers…” message, but nothing happens.

I’ve never had a problem with Browsersync before and often use it for Wordpress development, but now that I’m using it for a .net project it’s giving me such a headache trying to get it to work right. I’ve been battling this issue for well over a week and it’s incredibly frustrating that I can’t seem to get any answers anywhere.

1reaction
Syed-Alicommented, Sep 8, 2020

Below reload function works for me instead of direct call browsersync.reload. I got the exact issue like you mentioned.

const browsersync = require('browser-sync').create();

function reload(cb) {
    browsersync.reload();
    cb();
}

watch([files.scssPath, files.jsPath],
        series(
            parallel(scssTask, jsTask),
            reload
        )
    );
Read more comments on GitHub >

github_iconTop Results From Across the Web

node.js - Browsersync not reloading browser or injecting css
Right, it does state that, but it is not reloading the browser. Browsersync also fails to inject my css into the browser as...
Read more >
Browser Sync not refreshing after injecting css - sage
The problem I'm having is that browser sync is not refreshing once the new css is injected. Browser sync is working as I...
Read more >
Browsersync reloading the page instead of injecting css
I'm using Browsersync to watch for file changes, and it works perfectly, but instead of injecting css changes, it realods the whole page...
Read more >
HOW TO: CSS streaming/injection with Browsersync
Minimal changes are required to gain the benefits of CSS injection for your development. The Browsersync documentation does detail how to stream changes...
Read more >
Browsersync not injecting CSS or JS files [#3086572]
But when I try to Browsersync with a "live" website, the changed/generated CSS and JS is not being injected into the browser.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found