Search code examples
cssautomationsassgulpsource-maps

How to write two CSS files: with and without sourcemap


I need to have two merged CSS files in one directory - one with sourcemap and another without. What I tried for example is something like this :

.pipe(sourcemaps.init())
.pipe(concat('xxx.dev.min.css'))
.pipe(sourcemaps.write())
.pipe(gulp.dest(cssDir))
.pipe(sourcemaps.init({loadMaps:true}))
.pipe(concat('xxx.min.css'))
.pipe(sourcemaps.write('/dev/null', {addComment: false}))
.pipe(gulp.dest(cssDir))

All my trying resulted in either both files having a sourcemap, both not having a sourcemap or one having sourcemap based on another, not on original files.

Can this be achieved with only gulp-sourcemaps and how and if not, then how?


Solution

  • I think the following should work:

    gulp.task('default', function() {
      return gulp.src(['js/one.css', 'js/two.css'])
        .pipe(sourcemaps.init())
        .pipe(concat('withoutSourcemap.css'))
        .pipe(gulp.dest('dist'))
        .pipe(concat('withSourcemap.css'))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('dist'));
    });
    

    This sends the concatenated withoutSourcemap.css to the destination directory before source mappings have been generated. We then basically just rename the file to withSourcemap.css. Only after all that is the source map written to the stream and sent to the destination directory.

    EDIT: This is the generated withSourcemap.css in my case:

    .one { color:red; }
    
    .two { color:blue; }
    
    /*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm9uZS5jc3MiLCJ0d28uY3NzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUNEQTtBQUNBIiwiZmlsZSI6IndpdGhTb3VyY2VtYXAuY3NzIiwic291cmNlc0NvbnRlbnQiOlsiLm9uZSB7IGNvbG9yOnJlZDsgfVxuIiwiLnR3byB7IGNvbG9yOmJsdWU7IH1cbiJdLCJzb3VyY2VSb290IjoiL3NvdXJjZS8ifQ== */
    

    Base64-decoding the embedded source map yields the following:

    {"version":3,"sources":["one.css","two.css"],"names":[],"mappings":"AAAA;AACA;ACDA;AACA","file":"withSourcemap.css","sourcesContent":[".one { color:red; }\n",".two { color:blue; }\n"],"sourceRoot":"/source/"}