-->

How to setup Gruntfile.js to watch for SASS (compa

2019-02-22 16:05发布

问题:

I'm new to using gruntjs and nodejs. I wanted to know how can I setup the gruntfile so that it watches both the sass files and the js files compiles using watch.

This is what I have so far:

module.exports = function ( grunt ) {

  "use strict";
  require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks);

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    compass: {
      dist: {
        options: {
          config: 'config.rb',
          watch: true
        }
      }
    }
  });

  grunt.registerTask('default', []);

};

Any help will be much appreciated. Thank you!

回答1:

Try grunt-contrib-watch with grunt-contrib-sass. They're both Grunt plugins specifically for this kind of thing:

    sass: {
        dist: {
            options: {
                style: 'compressed'
            },
            files: {
                'css/build/global.css': 'scss/screen.scss'
            }
        } 
    },


    watch: {

        css: {
            files: ['scss/*.scss'],
            tasks: ['sass'],
            options: {
                spawn: false
            }
        } 
    },

The watch plugin configuration above will watch for changes in any .scss files, and will run the sass tasked (also defined above). You can even hook into livereload this way. You can also have multiple watches (the above only defines a css watch); creating a second watch to minify JS would be easy with grunt-contrib-uglify

I have an example you can look at that also concatenates JavaScript and does some minification with grunt-contrib-uglify. Here is the example.