gulp-sourcemaps points sources to wrong directory

2k views Asked by At

I'm trying to create source maps for my sass and js files with gulp-sourcemaps, but the path in sources: [ ... ] is always only relative to the source and not to the destination directory.

My project structure looks like this:

project
|-- public/
|   |-- css/
|   |   |-- main.scss
|   |   `-- dashboard.scss
|   |-- js/
|   |   |-- dashboard/
|   |   |   `-- dashboard.js
|   |   `-- app.js
|   |-- index.html
|   |-- app.min.js
|   |-- app.min.js.map
|   |-- style.css
|   `-- style.css.map
`-- gulpfile.js

And these are my two gulp tasks:

gulp.task('sass', function() {
    // only need main.scss because I'm using @import
    return gulp
        .src('./public/css/main.scss')
        .pipe(sourcemaps.init())
            .pipe(sass())
        .pipe(rename('style.css'))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./public'));
});

gulp.task('uglify', function() {
    return gulp
        .src(['./public/js/app.js', './public/js/**/*.js'])
        .pipe(sourcemaps.init())
        .pipe(concat('app.concat.js'))
            .pipe(uglify())
        .pipe(rename('app.min.js'))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('./public'));
});

After running those tasks the map files look like this:

{"version":3,"sources":"main.scss","dashboard.scss"], ... }
{"version":3,"sources":["app.js","dashboard/dashboard.js"], ... }

But I would expect them to be relative their actual directory

{"version":3,"sources":["css/main.scss","css/dashboard.scss"], ... }
{"version":3,"sources":["js/app.js","js/dashboard/dashboard.js"], ... }

So how can I get the desired result? What's wrong with my configuration?

1

There are 1 answers

2
Anthony Sneed On

To control the path of sources in a sourcemap file using gulp-sourcemaps, you should pass an options parameter to the sourcemaps.write command, in which you specify a relative directory for sourceRoot. For example:

gulp.task('javascript', function() {
  var stream = gulp.src('src/**/*.js')
    .pipe(sourcemaps.init())
      .pipe(plugin1())
      .pipe(plugin2())
    .pipe(sourcemaps.write({includeContent: false, sourceRoot: '/src'}))
    .pipe(gulp.dest('dist'));
});

This snippet is taken from the gulp-sourcemaps documentation. For an example, see this GitHub repository, where I use gulp-sourcemaps with gulp-typescript to map generated javascript source files back to typescript files.