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.

How to compile only changed files?

See original GitHub issue

I need to compile project with some separate css: public.sass, landing.sass and etc. Task ‘sass-agentcar’ compiled 1.85 sec, task ‘watch’ that watched “gulp.src(‘./sass/*/.{scss,sass}’)” compiled 4+ sec and recompiled all files in /sass directory. How to prettify code? How to compile only changed files?

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

gulp.task('sass-agentcar', function () {
    return gulp.src(['./sass/agentcar.sass', './sass/agentcar/*.sass'])
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            indentedSyntax: true,
            errLogToConsole: true,
            outputStyle: 'compressed',
        }))
        // .pipe($.autoprefixer('last 3 version'))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest('css'));
});
gulp.task('sass-public', function () {
    return gulp.src(['./sass/public.sass', './sass/public/*.sass'])
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            indentedSyntax: true,
            errLogToConsole: true,
            outputStyle: 'compressed'
        }))
        .pipe($.autoprefixer('last 3 version'))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest('css'));
});
gulp.task('sass-print', function () {
    return gulp.src(['./sass/print.sass', './sass/print/*.sass'])
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            indentedSyntax: true,
            errLogToConsole: true,
            outputStyle: 'compressed'
        }))
        .pipe($.autoprefixer('last 3 version'))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest('css'));
});
gulp.task('sass-landing', function () {
    return gulp.src(['./sass/landing.sass', './sass/landing/*.sass'])
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            indentedSyntax: true,
            errLogToConsole: true,
            outputStyle: 'compressed'
        }))
        .pipe($.autoprefixer('last 3 version'))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest('css'));
});
gulp.task('scss-bootstrap', function () {
    return gulp.src(['./sass/bootstrap.scss'])
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            errLogToConsole: true,
            outputStyle: 'compressed'
        }))
        .pipe($.autoprefixer('last 3 version'))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest('css'));
});

gulp.task('watch', function () {
    gulp.watch(['./sass/agentcar.sass', './sass/agentcar/*.sass'], ['sass-agentcar']);
    gulp.watch(['./sass/public.sass', './sass/public/*.sass'], ['sass-public']);
    gulp.watch(['./sass/print.sass', './sass/print/*.sass'], ['sass-print']);
    gulp.watch(['./sass/landing.sass', './sass/landing/*.sass'], ['sass-landing']);
    gulp.watch(['./sass/bootstrap.scss'], ['scss-bootstrap']);
});

gulp.task('sass', ['sass-agentcar', 'sass-public', 'sass-print', 'sass-landing', 'scss-bootstrap'])
gulp.task('default', ['sass', 'watch']);

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:8

github_iconTop GitHub Comments

1reaction
zebapycommented, Mar 16, 2015

Try gulp-watch

https://github.com/gulpjs/gulp/blob/master/docs/recipes/rebuild-only-files-that-change.md

Also you should be able to have 1 gulp sass task for this now, with gulp-watch.

gulp.task('sass', function() {
  return gulp.src('./sass/*.scss')
     .pipe($.watch('./sass/*.scss')
     .pipe($.sass())
     ...
     .pipe(gulp.dest('./css');
}

Since you have non-partial files, they should compile into individual files on their own and there’s no need to have a task for each one.

Just be sure your partials that are referenced (@import) in the main file have the correct path.

0reactions
Sinatorcommented, Jun 7, 2018

Translation into English via Google, if something kicks him))

It turned out that only the modified file was compiled!

The output is: file.scss  - file.css  - file.min.css  - file.min.css.map

It did not work either to beat Watcher, that he would immediately create the file after the “oneSassFileCompile” function was launched, the files were created only after the Watcher stop.

Exit the situation - launch the assistant task. But again did not find how to transfer parameters. I had to resort to an external variable, I hope it does not work out that many files changed immediately and this variable did not manage to skip all the files.

Sorry for my english. And for my script too, the first time I write to NodeJS and the first time I ran into Gulp!

If it turns out to throw a parameter directly into the subtask, or even better to force the files to be created immediately when the function is called in Watcher, I will be very glad to see the solution!

tags: gulp sass watch only one file change and compile css autoprefixer minify and map

gulpfile.js code:

// Variables 
var gulp        = require('gulp'),
    argv        = require('yargs').argv,
    sass        = require('gulp-sass'),
    rename      = require('gulp-rename'),
    //cssmin      = require('gulp-cssnano'), - a very long initialization, because of what is not convenient for a constant launch, but on the watcher will probably rise norms
    cleanCSS    = require('gulp-clean-css'),
    prefix      = require('gulp-autoprefixer'),
    plumber     = require('gulp-plumber'),
    notify      = require('gulp-notify'),
    sassLint    = require('gulp-sass-lint'),
    sourcemaps  = require('gulp-sourcemaps');

// Temporary solution until gulp 4
// https://github.com/gulpjs/gulp/issues/355
var runSequence = require('run-sequence');

// Settings
var sassProjectPath = 'templates/**/*.scss';
var sassOptions     = {
    outputStyle: 'expanded'
};
var prefixerOptions = {
    browsers: ['last 5 versions'],
    cascade: true
};


// Secondary functions
var displayError = function(error) {
    // Initial building up of the error
    var errorString = '[' + error.plugin.error.bold + ']';
    errorString += ' ' + error.message.replace("\n",''); // Removes new line at the end

    // If the error contains the filename or line number add it to the string
    if(error.fileName)
        errorString += ' in ' + error.fileName;

    if(error.lineNumber)
        errorString += ' on line ' + error.lineNumber.bold;

    // This will output an error like the following:
    // [gulp-sass] error message in file_name on line 1
    console.error(errorString);
};
var onError      = function(err) {
    notify.onError({
        title:    "Gulp",
        subtitle: "Failure!",
        message:  "Error: <%= error.message %>",
        sound:    "Basso"
    })(err);
    this.emit('end');
};


// BUILD SUB-TASKS
// ---------------


// Compiling a single single SASS file
var oneSassFileCompile = function(filePath, destinationDir){
    var fullFileName, fileName, baseDir;

    // Checking the parameters
    if(!filePath) {
        console.log('param filePath miss');
        return false;
    }

    // Find file paths
    fullFileName    = filePath.replace(/\\/g,'/').replace(/.*\//, '');
    fileName        = fullFileName.replace('.'+ fullFileName.split('.').pop(), '');
    baseDir         = filePath.replace(fullFileName, '');

    // If you do not specify a folder to save, use the current
    destinationDir         = destinationDir || baseDir;

    // Compile
    return gulp.src(filePath)
        // Error Handler
        .pipe(plumber({errorHandler: onError}))
        // For generic style.css.map
        .pipe(sourcemaps.init())
        // The actual compilation
        .pipe(sass(sassOptions))
        // Adding Manufacturer Prefixes
        .pipe(prefix(prefixerOptions))
        // Call the file
        .pipe(rename(fileName +'.css'))
        // Save the compiled version
        .pipe(gulp.dest(destinationDir))

        // Compress CSS
        //.pipe(cssmin())
        .pipe(cleanCSS())
        // Rename the suffix
        .pipe(rename({suffix: '.min'}))
        // Save the .map
        .pipe(sourcemaps.write('./'))
        // Save the compressed file
        .pipe(gulp.dest(destinationDir));
};

// Task to start compiling a specific file
// For PHPStorm File Watcher
gulp.task('sass-file', function() {
    var filePath        = argv.filePath,
        destinationDir  = argv.destDir;

    // Checking the parameters
    if(!filePath) {
        console.log('argv --filePath miss');
        return false;
    }
    return oneSassFileCompile(filePath, destinationDir)
});


// Compiling all SASS project files
// TODO - customize the paths and check
gulp.task('sass-project', function() {
    return gulp.src(sassProjectPath)
        .pipe(plumber({errorHandler: onError}))
        .pipe(sourcemaps.init())
        .pipe(sass(sassOptions))
        .pipe(prefix(prefixerOptions))
        .pipe(rename(fileName +'.css'))
        .pipe(gulp.dest('./'))

        // Compress CSS
        //.pipe(cssmin())
        .pipe(cleanCSS())
        .pipe(rename({suffix: '.min'}))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./'));
});


// Task checks the SASS project files
// TODO - customize the paths and check
gulp.task('sass-lint', function() {
    gulp.src(sassProjectPath)
        .pipe(sassLint())
        .pipe(sassLint.format())
        .pipe(sassLint.failOnError());
});


// Watcher for all SASS project files
// An auxiliary variable to transfer the file path from the watcher to the task
var sassWatchFilePath = '';
gulp.task('sass-watch', function() {
    gulp.watch(sassProjectPath, function(watchEvent){
        console.log('Watcher catch: '+ watchEvent.type +' :: '+ watchEvent.path);

        // Skip deleting
        if(watchEvent.type === 'deleted')
            return;

        // We set the variable with the path and start the helper
        sassWatchFilePath = watchEvent.path;
        gulp.start('sass-watch-helper');
    });
});
//Taks helper, if you immediately call "oneSassFileCompile" in sass-watch,
// then the files are not created until the process ends. watcher = (
gulp.task('sass-watch-helper', function() {
    var tmpPath = sassWatchFilePath;
    sassWatchFilePath = null;
    // Compilation
    return oneSassFileCompile(tmpPath);
});


// BUILD TASKS
// ------------


// Default task
gulp.task('default', function(done) {
    runSequence('sass-project', 'sass-watch', done);
});

// Project Collector
gulp.task('build', function(done) {
    runSequence('sass-project', done);
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

How do I make Makefile to recompile only changed files?
I have been struggling a bit to get make to compile only the files that have been edited. However I didn't have much...
Read more >
how to build with make so that only the changed files get build
First, you have to remove the clean dependency from your JYOTI target. Otherwise, everything is always built from scratch.
Read more >
How to rebuild only changed files?
I do small change in main.cpp and do run/build. CLion call cmake to rebuild all. Note: cmake alone can rebuild only changed files...
Read more >
Avoiding Compilation (GNU make)
Use the command ' make ' to recompile the source files that really need recompilation, ensuring that the object files are up-to-date before...
Read more >
compiling only the changed files in the project - Keil forum
Press the 'Build Target' button instead of the 'Rebuild all Target files' button. Note that using the SRC directive forces files to be ......
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