Browsersync in Gulp keeps triggering numerous reloads every time a file is changed

As I utilize browsersync with Gulp for running specific tasks upon file changes, I notice that each time I save a file, my terminal displays 10+ [BS] Reloading Browsers... messages and the overall performance suffers.

Below is an outline of my gulpfile:

gulp.task('bowerJS', function() {
  gulp.src(lib.ext('js').files)
    .pipe(concat('lib.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('app/assets/js'));
});

gulp.task('bowerCSS', function() {
  gulp.src(lib.ext('css').files)
    .pipe(concat('lib.min.css'))
    .pipe(gulp.dest('app/assets/css/'));
});


// Task to compile less into CSS & auto-inject it into browsers
gulp.task('less', function() {
    gulp.src('./app/css/*.less')
        .pipe(less())
        .pipe(autoprefixer({
          browsers: ['last 2 versions'],
          cascade: false
        }))
        .pipe(gulp.dest('app/assets/css'))
        .pipe(browserSync.stream());
});

// Rendering Jade templates as HTML files

gulp.task('templates', function() {
  gulp.src('views/**/*.jade')
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('app/src/'))
});

gulp.task('php', function() {
    php.server({ base: 'app', port: 8123, keepalive: true});
});
gulp.task('serve', ['bowerJS', 'bowerCSS', 'less', 'templates', 'php'], function() {


    var proxyOptions1 = url.parse('http://some-site:1234');
        proxyOptions1.route = '/api/hi';

    browserSync({
        port: 8999,
        proxy: '127.0.0.1:8123',
        middleware: [
                proxy(proxyOptions1),
                history()
        ],
        notify: false
    });


    gulp.watch("app/assets/css/*.less", ['less']);
    gulp.watch("app/**/*.html").on('change', browserSync.reload);
    gulp.watch("app/assets/js/*.js").on('change', browserSync.reload);
    gulp.watch("views/**/*.jade", ['templates']);
});

Need some insights on what could be causing these issues. Any suggestions?

Answer №1

Instead of using browserSync.reload, opt for the simpler browserSync.stream and add the option once: true as shown below:

browserSync.stream({once: true})

This should function perfectly.

Answer №2

I was able to resolve the issue by using the awaitWriteFinish option in Chokidar.

Here is an example:

browserSync.init({
    server: dist.pages,
    files: dist.css + '*.css',
    watchOptions: {
        awaitWriteFinish : true
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the message displayed in the user interface after the view has been fully rendered in an Express application, following the execution of asynchronous

I have created a simple express app that reads files from a directory, renames them, zips the files asynchronously, and then renders another view. The file reading and renaming are done synchronously, while the zipping part is handled asynchronously. My cu ...

A guide on effectively utilizing the Map datatype in JavaScript

Recently, I've started delving into the world of es6 Map due to its unique features, but I have some reservations regarding pure operations. For example, when removing properties from objects, I usually use the following function: function cloneOmit ...

Issue connecting to MongoDB database from Node.js due to "ECONNREFUSED" error

I'm facing some challenges as a beginner and need help setting up a basic connection to mongodb from node.js on my Mac. I successfully installed mongodb using homebrew, started the server (mongod), and confirmed the connection using the mongo shell. ...

A guide on fetching the selected date from a datepicker in framework7 with the help of vuejs

Here is a snippet of the code for a component I am working on: <f7-list-input label=“Fecha de nacimiento” type=“datepicker” placeholder=“Selecciona una fecha” :value=“perfil.fecha_nacimiento” @input=“perfil.fecha_nacimiento = $event.t ...

Having trouble figuring out the console.log(JSON.stringify(req)) line in the middleware code

My challenge arises when I attempt to connect to my Express 4 node.js websocket server from the client and log req. The program becomes unresponsive, still managing to accept new connections and execute them up until the same console.log statement before ...

using javascript to retrieve php variables

After creating a webpage, setting up Apache2 on an Ubuntu server to access it over the internet, and installing PHP5 and MySQL, I encountered issues with accessing database information on my page through a .php file. Despite having a file named test.php th ...

Confirming an authorization?

I have been working on this code and it is almost perfect, but I am struggling to understand why it needs to validate the 0 or 10 in order to work correctly. The issue I am facing is with a validation where the button should be deactivated when the counte ...

Transmitting information from the form to the server

When trying to send formdata to an endpoint, I encounter an issue with the required data fields: token_key, customer_id, folder_id, document_id, file The steps I follow are as follows: In my HTML file: submitBtn.addEventListener("click", funct ...

Is there a way to transform data retrieved from a MySQL database into snake case and then insert it into the value field for every item in a list using EJS and Express?

Currently, I am in the process of creating a form to input data into a local business database. While I was successful in pulling data dynamically from my MySQL database and populating it into a drop-down list, I encountered an issue with assigning values ...

Issue: No build script found in npm5Problem:

To start testing with NPM 5, execute npm test command: "scripts": { "build": "babel src -d dist", "test": "npm run build; mocha --require 'babel-polyfill' --compilers js:babel-register './tests/**/*.spec.js'" }, An error occ ...

Accessing and fetching data from a PostgreSQL database using JavaScript through an API

I am currently working with an npm package called tcmb-doviz-kuru to fetch currency data from an API and then insert it into my database. However, I am facing an issue with mapping the data to properly insert the values. Below is my code snippet: var tcmbD ...

What is the method for individually extracting values from HTML using class li?

Is there a way to extract each value from the HTML within the li class separately? I have tried various methods but none have been successful. Can anyone provide a solution? Here is my JavaScript code: $(document).ready(function() { $(".list-grou ...

An index that doesn't quite live up to its unique reputation

I'm experimenting with intentionally creating and writing a duplicate entry on a unique index in MongoDB for testing purposes. Here's the code I am using: db.collection("foo").ensureIndex({a: 1}, {unique: true}, function () { db.collection(" ...

Tips for utilizing the express-uploadfiles package

I am encountering an issue when trying to print the name of a file to the console. When I provide the server path along with the file, I receive the following error message: TypeError: Cannot read properties of undefined (reading 'file') This i ...

What is the best way to upload a JSON file onto a local server?

After struggling for the past two hours trying to solve a problem I encountered, I've come to realize that accessing a local JSON file named data.json from my project directory is not possible due to cross-origin requests limitations. In order to acce ...

Troubleshooting Missing Exports from Local Modules in React Vite (Transitioning from Create React App)

I have encountered an issue while trying to import exported members from local nodejs packages in my project. Everything was working fine with the standard CRA webpack setup, but after switching to Vite, I started getting the following error: Unca ...

Having trouble applying styles to a component using forwardRef

I'm relatively new to React and still trying to wrap my head around the component's lifecycle. However, the issue at hand is proving to be quite perplexing. One thing that confuses me is why adding "setState(10);" causes the style of the "Test" ...

encountering a problem while utilizing the -g flag in npm

Everytime I attempt to install a package globally, I encounter numerous errors. Please take a look at the screenshot below for more information. Click here to view the errors in the terminal Appreciate your assistance. ...

Faulty toggle functionality within a JavaScript-created accordion panel

HTML I'm looking to add a FAQ question within the div with the class "section-center" <body> <section class="questions"> <div class="title"> <h2>FAQ SECTION</h2> < ...

Assistance with designing in JavaScript and Python

Currently, I have a setup where my external website is extracting data from an iframe within our internal company intranet using Javascript. The extraction process is successful, but now I am faced with the challenge of accessing this harvested data in ord ...