如何使用自动前缀和缩小为sass文件生成正确的源映射

时间:2019-05-13 23:16:55

标签: css sass gulp minify autoprefixer

我正在尝试配置gulp以将SASS(* .scss)文件转换为CSS,自动前缀,并且还想为已编译的CSS文件生成一个源映射文件。我正在尝试创建两个CSS文件,一个是普通文件,另一个是其他压缩文件。这两个CSS文件都需要具有源映射。我有以下gulp配置文件,但是由此生成的源映射不正确。当我运行不带自动前缀的gulp任务时,一切都很好,但是使用自动前缀,源地图就混乱了,即在chorme开发工具中打开时,它指向不正确的行号。

我尝试了多种配置,例如内联源地图和单独的源地图。我什至尝试过在自动添加前缀之前加载源地图,然后在自动添加前缀之后将其写入文件。

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);
};

即使在自动前缀之后,我也希望正确的源地图,但是在当前设置下,我得到的行号不正确。 (对于源.scss文件中嵌套元素中子元素的所有样式,sourcemap都指向根元素。)

例如,在下面的示例中,当我检查h2元素时,源映射会指向根元素.shopping-cart(行#445)而不是(行#459)

enter image description here

1 个答案:

答案 0 :(得分:0)

您是否有理由在sourcemaps.init-> buildStyles内两次致电source

sourcemaps.init应该先于sourcemaps.write . In your code, you have it the other way around for source in buildFiles`。

老实说,对我来说,看起来您的构建比所需的复杂得多,这正在引起问题。

See docs for reference


还有,如果您有源地图,为什么还要使用非最小化的代码?