sassgruntjsgrunt-contrib-sass

Grunt/SASS: Output CSS into a single file, and keep source mapping true to multiple source files


I'm setting up SASS source maps (grunt-contrib-sass) in a Grunt task. Ideally all my projects' CSS would be combined into one file, and keep source maps true to the original source.

My initial thought was that it would be easiest just to keep the output source in separate files, which would make it easy, since mapping would be 1-to-1, with one .css output file for each .scss source file. But that wouldn't be an ideal solution going forward for the rest of our projects, as we'd like to keep HTTP requests to a minimum.

I can see how I can combine my source files, and output SASS from that, for one output file, or I could concat my .css output after SASS exports it, but obviously, mapping would not be true in either of these implementations.

It seems like this would have to be a feature of grunt-contrib-sass, but I'm not finding such a feature.

My SASS config looks like this:

    sass: {
        dist: {
            files: [{
                expand: true,
                cwd: './src/',
                src: ['**/*.scss', '**/*.sass'],
                dest: './dist',
                ext: '.css'
            }],
            options: {
                style: 'compressed',
            }

        }
    },

I tried the style options in the documentation, and found only two of the four, 'compressed' and 'expanded' actually work. 'compact' and 'nested' do not work. I don't see an option that looks specific to what I need.

How can I output from SASS into a single CSS file, and keep source mapping true to multiple source files?


Solution

  • For outputting all of your styles into a single CSS stylesheet, I would recommend having one main.scss file in the root of your scss directory where you put @import statements to include all of the other scss files you'd like in the correct order.

    Make sure to prepend all of the partial filenames (the files you are importing) with an underscore _ like _homepage-styles.scss. This is important as it tells the sass compiler to ignore compiling these files down to their CSS equivalents. Thus, the compiler will output a CSS file for each SCSS file without the underscore _.

    So your output would be main.css


    For sourcemaps, add this under the options on your SASS config:

    options: {
        'sourcemap': 'auto'
    }
    

    It should map down to the individual scss files. :)