I am trying to configure gulp to convert SASS (*.scss) files into CSS, autoprefix and also would like to generate a sourcemap file for the compiled CSS file. I am trying to create two css files one normal and other minified version of it. Both of these CSS files needs to have sourcemaps. I have the following gulp config file however the sourcemaps generated by this is incorrect. When I run the gulp task without autoprefixer then everything is fine however with autoprefixer the sourcemaps is messed up i.e it points to the incorrect line number when opened up in a chorme dev tools.
I have tried multiple configurations like inline sourcemaps and separate sourcemaps. I even tried loading the sourcemaps before autoprefixing and then writing it to a file after autoprefixing is done.
const { src, dest } = require('gulp');
const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const clone = require('gulp-clone');
const merge = require('merge-stream');
const rename = require('gulp-rename');
const sourcemaps = require('gulp-sourcemaps');
const sassUnicode = require('gulp-sass-unicode');
const prefix = require('autoprefixer');
const minify = require('cssnano');
const {paths} = require('./config.js');
/*
* Node Sass will be used by defualt, but it is set explicitly here for -
* forwards-compatibility in case the default ever changes
*/
sass.compiler = require('node-sass');
sass_options = {
// outputStyle: 'compressed',
outputStyle: 'compact',
// outputStyle: 'nested',
// outputStyle: 'expanded'
sourceComments: false,
precision: 10
};
prefix_options = {
browsers: ['last 2 versions', '> 5%', 'Firefox ESR'],
cascade: false
};
minify_options = {
discardComments: {
removeAll: true
}
}
// Process, compile, lint and minify Sass files
const buildStyles = function (done) {
var source = src(paths.styles.input)
.pipe(sourcemaps.init())
.pipe(sass(sass_options).on('error', sass.logError))
// .pipe(sassUnicode())
.pipe(sourcemaps.write({includeContent: false}))
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(postcss([prefix(prefix_options)]));
// Create non-minified css file and its sourcemaps
var pipe1 = source.pipe(clone())
.pipe(sourcemaps.write('.'))
.pipe(dest(paths.styles.output));
// Create minified css file and its sourcemaps
var pipe2 = source.pipe(clone())
.pipe(rename({ suffix: '.min' }))
.pipe(postcss([minify(minify_options)]))
.pipe(sourcemaps.write('.'))
.pipe(dest(paths.styles.output));
return merge(pipe1, pipe2);
};
I expect correct sourcemaps even after autoprefixing however with the current setup I am getting incorrect line numbers. (for all the styles of a child element in a nested element in the source .scss file the sourcemap points to the root element).
For instance, in the below example, when I inspect h2 element the sourcemaps points to the root element .shopping-cart (line#445) instead of (line#459)