What is the best way to have gulp monitor my sass file updates and generate a single css file?

I'm currently working on a project using ASP.NET MVC 5 framework and Visual Studio 2013. In order to automate the process of compiling my sass files and publishing them into a bundle.css file, I decided to utilize gulp.

Here are the steps I took:

  1. Installed NodeJs on my machine
  2. Installed gulp globally by running npm install -g gulp
  3. Created a file named gulpfile.js in the root of my project
  4. Generated the package.json file using npm init
  5. Added gulp to my development dependencies with the command npm install gulp --save-dev
  6. Implemented the code below in my gulpfile.js
  7. Ran the gulp command from the console, which provided the following output

    Using gulpfile ...gulpfile.js

    Starting 'watch'...

    Finished 'watch' after 21 ms

    Starting 'default'...

    Finished 'default' after 31 µs

However, despite coding in ~/Assets/Sass/**/*.sass, nothing is being saved into ~/Public/Css/bundle.css as expected.

Below is the content of my gulpfile.js:

const gulp = require('gulp'),
      sass = require('gulp-ruby-sass');

// Default task triggered when starting the runner
gulp.task('default', ['watch']);

// Watch for changes in the sass directory and trigger "compileSass" upon save
gulp.task('watch', function(){

    //Watch any change in the sass directory and trigger the "compileSass" for every save
    gulp.watch('~/Assets/Sass/**/*.sass', ['compileSass']);

});

// Compiling the sass files
gulp.task('compileSass', () =>
    sass('~/Assets/Sass/**/*.sass')
        .on('error', sass.logError)
        .pipe(gulp.dest('~/Public/Css/bundle.css'))
);

What could be missing here? How can I ensure that watch is activated and tasks are executed after each save?

Update:

I made the switch from gulp-ruby-sass plugin to gulp-scss. Now, the task runs every time I save a scss file but it still doesn't update the destination file.

Here's how my revised gulpfile.js now looks like:

const gulp = require('gulp'),
      scss = require('gulp-scss');

// Default task triggered when starting the runner
gulp.task('default', ['watch']);

// Watch for changes in the "Scss" directory and trigger "compileScss" upon save
gulp.task('watch', function(){

    //Watch any change in the "Scss" directory and trigger the "compileScss" for every save
    gulp.watch('./Assets/Scss/**/*.scss', ['compileScss']);

});

// Compile the "Scss" files
gulp.task('compileScss', function () {
    gulp.src('./Assets/Scss/**/*.scss')
        .pipe(scss({ "bundleExec": true }))
        .pipe(gulp.dest('./Public/Css/bundle.css'));
});

Answer №1

If you're encountering issues with gulp-watch, you might need to ensure that the 'require' statement is included:

var watch = require('gulp-watch');

According to gulp-watch documentation:

watch(glob, [options, callback]) sets up a watcher to keep an eye on files specified by glob, which can be a string or array of strings.

It returns a stream that will output vinyl files (with additional event property) corresponding to file system events.

Make sure to provide a function as just using a task name won't suffice.

Consider utilizing gulp-batch to handle multiple tasks within your watch setup:

npm install gulp-batch --save-dev

Your watch configuration should look like this:

// Listener Task
gulp.task('watch', function(){

   var watch = require('gulp-watch');
   var batch = require('gulp-batch');

    // Watch changes in Sass directory and run "compileSass" task on save
    watch('~/Assets/Sass/**/*.sass', batch(function (events, done) {
        // Execute compileSass task
        gulp.start('compileSass', done);

    }));

});

Edit:

In Visual Studio 2015, you can execute tasks through the "Task Runner Explorer" window.

Alternatively, running gulp-watch in the terminal should automatically trigger your compile task upon detecting changes in the specified files, irrespective of where they were edited.

Answer №2

Important factors to verify include the presence of folders, correctness of file names, and checking read/write permissions.

Below is a sample gulpfile.js showcasing the usage of gulp.watch and gulp-load-plugins in a Zurb Foundation 6 project with the assistance of (foundation-cli).

Please take note that

.pipe(gulp.dest('../your/path/css'));
does not contain a ~, specify a file name or extension. It exclusively denotes a path. The default name given to the file placed in that path is style.css, as the source file's name is style.scss. Refer to line gulp.src('scss/style.scss').

var gulp = require('gulp');
var $    = require('gulp-load-plugins')();

// Various locations of SCSS for combination
var sassPaths = [
  'bower_components/foundation-sites/scss',
  'bower_components/motion-ui/src'
];

gulp.task('sass', function() {
  return gulp.src('scss/style.scss')           // Source file in SCSS
    .pipe($.sass({
      includePaths: sassPaths,
      outputStyle: 'compressed'               // if css compressed **file size**
    })
      .on('error', $.sass.logError))
    .pipe($.autoprefixer({
      browsers: ['last 2 versions', 'ie >= 9']
    }))
    .pipe(gulp.dest('../your/path/css'));     // Output destination
});

gulp.task('default', ['sass'], function() {
  gulp.watch(['scss/**/*.scss'], ['sass']);   // Files being watched
});

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

Ensuring that a TypeORM column has been updated

Currently, I am utilizing TypeORM with the ActiveRecord design pattern and have created this entity: @Entity() export class User { @PrimaryGeneratedColumn() public id: number; @Column() public username: string; @Column() public password: stri ...

Is it possible to include a parameter in module.exports?

A module in my application runs a query and uses express to display the results. module.exports.runQuery =function(req,res){ //establishing connection connection.on('connect', function(err) { console.log("success"); //if connec ...

Ways to respond to the client within the onProxyReq function of the http-proxy-middleware

I am currently working on setting up a reverse proxy using express and [email protected] with some validation included. The goal is to have the ability to check within the onProxyReq function and, if the validation fails, return an error to the caller ...

What's the trick to aligning navigation items side by side?

I'm currently working with the code snippet below: header { height: 110px; width: 100%; margin-bottom: 130px; position: fixed; top: 0; z-index: 11; /*additional styling removed*/ } nav ul { list-style: none; paddin ...

How many logical lines of code are in the Ubuntu operating system?

As I develop my web application, it is crucial for me to track the lines of code written in languages such as php, css, html, and JavaScript specific to the /var/www directory. However, when using the command line code counter tool, I find myself tempted ...

The installation of npm is encountering issues within the Jenkins pipeline, despite my efforts to configure it with a custom .nrpmrc file in the Npm

Check out my pipeline below: pipeline { agent any tools {nodejs "node10"} stages { stage('Build') { steps { withNPM(npmrcConfig: 'xxx') { sh "npm config ls" ...

Extract value from child div using JQuery and update text in another section of the page

Here is a fiddle showcasing the concept I am working on: https://jsfiddle.net/wvz9p3e7/1/ The code is written in PHP and involves a loop for cycling through 7 or 8 different garments. My goal is to have the window on the right side of the fiddle display t ...

What is the most effective way to configure the $PATH for npm?

I'm encountering a problem with the npm command. $ npm search npm ERR! Darwin 16.7.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "search" npm ERR! node v6.11.3 npm ERR! npm v3.10.10 npm ERR! search must be called with arguments npm ERR ...

The Media Queries in the Wordpress html5blank theme are failing to function properly

While using the html5blank theme to develop a WordPress site, I noticed that my media queries are functioning properly locally. However, when I add them to the WordPress style.css file, they seem to stop working. Even after stripping away all other media q ...

Encountering a TypeError while attempting to retrieve an instance of AsyncLocalStorage

In order to access the instance of AsyncLocalStorage globally across different modules in my Express application, I have implemented a Singleton class to hold the instance of ALS. However, I am wondering if there might be a more efficient way to achieve th ...

Styling elements with Css Flex in a single row

Hi there, I'm currently working on a project and I'm facing an issue with aligning all the items in the same row. I've attempted to use flexbox but the items end up overlapping each other and I'm unsure of how to resolve this issue. To ...

Enhancing 2D video viewing with Threejs interactivity

I want to create an interactive 2D video using three.js and maintain the aspect ratio of the video when resizing the browser window. Here is the code I am currently using: var camera, scene, renderer; var texture_placeholder, distance = 500; init() ...

Elastic Beanstalk hosted apps do not support the transmission of large files

I've been working on a web application that requires storing large files, specifically mp4 videos with sizes sometimes exceeding 100mb. However, I encountered an error when trying to upload these files from a static Angular website hosted in an S3 buc ...

What is the best way to retrieve the border-color inline style using jQuery?

I have a HTML tag like this. <span id="createOrderFormId:accountNo" style="border-color: red;"><</span> To retrieve the style value for the border-color property, I tried using the following jQuery code: $( document ).ready(function() { ...

Issue with Gulp.js: "gulp-chug" fails to watch multiple files and only runs one

Recently, I've delved into the world of Gulp and encountered an issue with getting gulp-chug to function correctly. Despite diligently following the instructions in the documentation, my gulpfile seems to only be watching a single file within specifi ...

Using JavaScript to alter CSS styles with dashes

Currently, I'm delving into the world of manipulating CSS using JavaScript: img.style.borderRadius = "100%"; img.style.border = "9px solid #ffffff"; img.style.boxShadow = "0 0 5px #00000070"; img.style.margin = "20px"; I'm wondering how to chan ...

I am facing an issue with Nestjs where it is unable to resolve my dependency, despite the fact that it is readily available within the

Encountering the following error: Error: Nest is unable to resolve dependencies of the CreateGroupTask (TaskQueueService, GroupsService, ?, GroupNotificationsService, GroupRepository, Logger). Please ensure that the argument dependency at index [2] is avai ...

Exploring the process of gathering information using Node.js' http.request

I am currently facing a challenge where I need to call a REST API URL in one method and then use the response from that call to form a subsequent query to another URL, let's say git, to fetch some information. Despite browsing through several examples ...

Tips for avoiding a ligature occurrence in a specific location

I am a fan of ligatures in general, as they improve readability. I want to implement them across all my HTML pages. However, there is this one word Hanftierheft (which is German and a compound word made up of Hanf, Tier, and Heft). I specifically do not w ...

How can you center the initial line of formatted text while keeping the rest left justified using just CSS?

I need help with formatting existing data without using JavaScript. The goal is to make the first line bold and centered, while the rest of the lines should be justify formatted. However, I'm having trouble achieving this as either the first line gets ...