BrowserSync / browser-sync

Keep multiple browsers & devices in sync when building websites. https://browsersync.io
https://discord.gg/2d2xUThp
Apache License 2.0
12.15k stars 754 forks source link

Browsersync not reloading or injecting css changes #1640

Open QuintonC opened 5 years ago

QuintonC commented 5 years ago

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

Affected platforms

Browsersync use-case

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'));
    });
mamashi commented 5 years ago

Hello,

Watch my issue :

https://github.com/BrowserSync/browser-sync/issues/1637

QuintonC commented 5 years ago

Hello,

Watch my issue :

1637

Nothing that was in your solution worked for me. My project runs locally on https://localhost:3000 and when I try to implement ANY of your changes it pushes me to https://localhost:3001 and doesn't work for anything at all.

QuintonC commented 5 years ago

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.

mamashi commented 5 years ago

Hello, Check in your code if browsersync inject the script for reloading like that (the body tag is needed):

<script async="" id="__bs_script__" src="http://localhost:3000/browser-sync/browser-sync-client.js?v=2.26.3"></script>

In pipe you just need .pipe(browserSync.stream()); normally after the dest. And in proxy config you put your vhost or your subdirectories browsersync create for you the localhost:3000.

QuintonC commented 5 years ago

It is not injecting the script into my source. I have a body tag, but once again.. I'm thinking this is probably more specific to a .net issue.

My reasoning for that is that the Index.cshtml page which loads by default does not have a body tag, but the shared template that it loads does have a body tag. I don't know if that has something to do with it or not, but I would assume that it's possible.

Here are the only four scripts included in my code when inspecting: image

I've tried streaming numerous different ways.

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.reload({stream: true}));
        // .pipe(reload({stream: true}));
});

Also, it's worth mentioning that if I set the app to run on localhost:3050, then set up Browsersync to proxy that address it will not load any information on localhost:3000 (the bs port).

If I run off of a serve task it will not work either.

Syed-Ali commented 3 years ago

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