Grunt lets you automate repetitive tasks such as minifying JavaScript or CSS files, running tests, and more. Grunt is fully integrated with Visual Studio 2015, so it's a great time to put it to use. In this article, we will see how to automate generating a minified CSS file from a SASS file:

The goal is also to generate a source map file from the SASS source file to simplify debugging:

We will need the following Nodejs packages:
To do this, declare them in the package.json file at the root of the project:
JSON
{
"version": "1.0.0",
"name": "Sample",
"private": true,
"devDependencies": {
"grunt": "^0.4.5",
"grunt-sass": "^0.17.0",
"grunt-autoprefixer": "^2.1.0",
"grunt-csswring": "^1.1.0",
"grunt-contrib-watch": "^0.6.1"
}
}
Do not forget to download the new modules:

Now we can use these modules in the grunt.js file:
JavaScript
module.exports = function (grunt) {
grunt.initConfig({});
grunt.loadNpmTasks("grunt-sass");
grunt.loadNpmTasks("grunt-autoprefixer");
grunt.loadNpmTasks("grunt-csswring");
};
We can now configure the three tasks:
JavaScript
grunt.initConfig({
sass: {
sample: {
options: {
style: "expanded",
sourceMap: true,
verbose: true
},
files: {
'wwwroot/css/site.css': "wwwroot/css/site.scss"
}
}
},
autoprefixer: {
sample: {
options: {
browsers: ["last 2 versions"],
diff: false,
map: true
},
files: {
'wwwroot/css/site.prefixed.css': "wwwroot/css/site.css"
}
}
},
csswring: {
sample: {
options: {
map: true
},
files: {
'wwwroot/css/site.prefixed.min.css': ["wwwroot/css/site.prefixed.css"]
}
}
}
});
To simplify running these three tasks, create an alias:
JavaScript
grunt.registerTask("style", ["sass", "autoprefixer", "csswring"]);
To start a Grunt task from Visual Studio, use the Task Runner Explorer:

The result is displayed in the console. If everything succeeds, all files are generated:

You can automate this task either by using grunt watch or by creating a binding in Visual Studio:

For this type of task, grunt watch (started on project load) is preferable because it avoids recompiling the entire project on every style change:
JavaScript
grunt.initConfig({
watch: {
styles: {
files: ["wwwroot/**/*.scss"],
tasks: ["styles"]
}
},
// code omitted for brevity
The entire CSS generation process is now automated. Each time a SASS file is modified, all tasks run in sequence to produce a prefixed, minified CSS file, complete with a sourcemap to simplify debugging.
Do you have a question or a suggestion about this post? Contact me!