Search code examples
sassgruntjsnode-sass

Using node-sass watch option with grunt-sass


How can configure grunt-sass to also watch for changes using the underlying node-sass watch option?

I understand I can achieve the same functionality with grunt-contrib-watch to watch for changes and re-run the grunt-sass task, but that will be slower since it will recompile the whole thing instead of just compiling the changes.

Thanks!


Solution

  • Answering my own question, in case this can help anyone else:

    The only way I found solving this, is using the node-sass CLI through grunt. To achieve this, install the amazing grunt-exec task and set it to run a command with the --watch option.

    An example usage (with support for several includePath directories):

    exec: {
       nodeSass: {
          cmd: function() {
             // Include path option string built from the gruntConfig.cssFiles array.
             var includeFilesOption = gruntConfig.cssFiles.map(function(cssFilePath) {
                return '--include-path ' + cssFilePath;
             }).join(' ');
    
             return 'node-sass app/scss/style.scss app/generated/style.css' + includeFilesOption + ' --watch';
          }
       }
    }
    

    You will also need to install node-sass via npm. In that case, you can simply add the following to your package.json file:

    "scripts": {
       "install": "npm install node-sass -g"
    },