Grunt concat + uglify with sourcemaps
Asked Answered
C

2

34

I use concat to merge JS files into one file and uglify to minimize the JavaScript. How can I create a sourcemaps file that uses the source JS files?

My current gruntfile:

concat: {
    options: {
        // define a string to put between each file in the concatenated output
        separator: ';'
    },
    dist: {
        // the files to concatenate
        src: ['<%= config.src %>/js/**/*.js'],
        // the location of the resulting JS file
         dest: '<%= config.dist %>/js/main.js'
    }
},

uglify: {
    dist: {
        files: {
            '<%= config.dist %>/js/main.min.js': ['<%= concat.dist.dest %>']
        }
    }
},
Clausius answered 11/9, 2014 at 16:49 Comment(0)
F
56

You need to enable source maps on both the concat and uglify tasks, and you must specify the sourceMapIn option for the uglify task.

Here's a sample grunt config:

concat : {
  options : {
    sourceMap :true
  },
  dist : {
    src  : ['www/js/**/*.js'],
    dest : '.tmp/main.js'
  }
},
uglify : {
  options : {
    sourceMap : true,
    sourceMapIncludeSources : true,
    sourceMapIn : '.tmp/main.js.map'
  },
  dist : {
    src  : '<%= concat.dist.dest %>',
    dest : 'www/main.min.js'
  }
}
Firmament answered 23/10, 2014 at 11:41 Comment(6)
This answer has been helping resolve a similar requirement (mapping uglify source to require source to individual require modules). Thanks!Dagny
This is working for me except the line numbers are wrong in the final map when using the minified js (chrome's console will point to line 320 for an error instead of line 290 for example). Do you have any idea why this is happening?Mycostatin
In my case the source maps are generated but unusable. When I set a breakpoint the code does not stop there. Seems like a general problem of uglifyjs that is not solved yet.Butch
Y0lk, Are you adding a banner that happens to be 30 lines long?Trulatrull
The sourceMapIn can be more conveniently specified as (based on #14208483): sourceMapIn: function(path) { return path + ".map"; } which is more generic and also supports multiple source files.Ciccia
Did anyone find a solution to the problem that it doesn't stop on breakpoints ? I am having the same issue. Everything seems to be working fine, but when I try to stop on breakpoints it just doesn't stop.Operant
B
-1

Per the grunt-contrib-uglify docs, you can enable sourcemap generation as part of the uglify process.

Your uglify config would look something like:

uglify: {
        dist: {
            files: {
                '<%= config.dist %>/js/main.min.js': ['<%= concat.dist.dest %>']
            },
            options: {
                sourceMap: true
        }
    },
Borne answered 6/10, 2014 at 12:15 Comment(1)
That is working if I would only use uglify, but I am using both uglify and concat.Clausius

© 2022 - 2024 — McMap. All rights reserved.