How do I generate sourcemaps for Uglified files using Grunt? - gruntjs

I have a Grunt project that uses both Browserify and Uglify. Here are the core bits of it:
browserify: {
myapp: {
options: {
transform: ['babelify'],
browserifyOptions: {
debug: true
},
},
src: 'src/index.js',
dest: 'build/myapp.js'
}
},
uglify: {
options: {
sourceMap: true,
banner: bannerContent
},
target: {
src: 'build/myapp.js',
dest: 'build/myapp.min.js'
}
},
It seems to generate a myapp.min.js.map file but it no longer has the raw sources in the source-map that existed prior to the Browserification.
Here's what the resultant source-map file contains:
{
"version":3,
"sources":[
"myapp.js"
],
"names":[
...
...
...
],
"mappings":".........",
"file":"myapp.min.js"
}
I've tried using the uglifyify transform for Browserify but that does not seem to generate as small files as the Uglify task.
I've also bumped all my dependencies to the latest but I haven't been able to resolve this issue.

grunt-contrib-uglify has a sourceMapIn option that allows you to specify the location of an input source map file from an earlier compilation - which in your scenario is the browserify task.
However, whilst setting browserifyOptions: { debug: true } in your browserify task does generate an inline source map in the resultant .js file (i.e. in build/myapp.js), the crux of the problem is twofold:
We don't have an external source map file that we can configure the sourceMapIn option of the subsequent grunt-contrib-uglify task to utilize.
grunt-browserify doesn't provide a feature to create an external .map file, it only creates them inline (see here)
To address the aforementioned issue consider utilizing grunt-extract-sourcemap to extract the inline source map from build/myapp.js (i.e. from the output file generated by your browserify task) after it has been produced.
Gruntfile.js
The following gist shows how your Gruntfile.js should be configured:
module.exports = function (grunt) {
grunt.initConfig({
browserify: {
myapp: {
options: {
transform: ['babelify'],
browserifyOptions: {
debug: true
},
},
src: 'src/index.js',
dest: 'build/myapp.js'
}
},
extract_sourcemap: {
myapp: {
files: {
'build': ['build/myapp.js']
}
}
},
uglify: {
options: {
sourceMap: true,
sourceMapIn: 'build/myapp.js.map'
},
target: {
src: 'build/myapp.js',
dest: 'build/myapp.min.js'
}
}
});
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-extract-sourcemap');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Note the order of the tasks in your task list is important.
grunt.registerTask('default', ['browserify', 'extract_sourcemap', 'uglify']);
};
Explanation
First the browserify task is invoked which outputs a new file (i.e. build/myapp.js) containing your bundled JavaScript and an "inlined" source map info. If you were to inspect the content of build/myapp.js at this stage it includes something like the following at the end:
//# sourceMappingURL=data:application/json;charset=utf-8;base64, ...
Next the extract_sourcemap task is invoked. This essentially extracts the "inlined" source map info from build/myapp.js and writes it to a new file named myapp.js.map which is saved in your build directory.
The original "inlined" source map info in build/myapp.js is replaced with a link to the newly generated source map file, i.e. myapp.js.map. If you inspect the content of build/myapp.js you'll now notice the following at the end of the file instead:
//# sourceMappingURL=myapp.js.map
Lastly the uglify task is invoked. Notice how its sourceMapIn option is configured to read build/myapp.js.map, i.e the source map file we generated at step 2.
This task creates your desired build/myapp.min.js file containing; your minified JS, and a link to a newly generated source map file build/myapp.min.js.map.
Note The final resultant file (i.e. build/myapp.min.js) now correctly maps back to the original src/index.js file and any file(s) that index.js itself may have import'ed or require()'d

Related

Grunt run task depending of file modified, it's possible?

can you help-me with this problem?
I need run a specific task depending of file modified, for example:
Modifie: _header.scss
Run: sass:header task
Modifie: _footer.scss
Run: sass:footer task
Modifie: _banners.scss
Run: sass:banners task
I've been trying to get the name of the file at save time to use it as a parameter, but I can not figure out ways to do this.
My project allows more people to work simultaneously but the work of defining which component of the project will be exported to CSS is manual, so I am trying to make this process of compiling the final CSS of each module as automatic.
My problem is how I can identify the name of the modified file, not the type of file.
Thank you very much!
It should look like this. When sass files are changed, grunt generates css files and copies (to dist directory) changed files only. Also as far as you can see connect and watch task implement live reload.
connect: {
options: {
port: ...
livereload: 35729,
hostname: '127.0.0.1'
},
livereload: {
options: {
base: [
'some dist'
]
}
}
},
// check that files are changed
watch: {
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'your dist/*.css'
]
},
// when sass file is changed, tasks will run
// newer:copy means that we have to do task copy with changed files only
sass: {
files: ['your dir/*.sass'],
tasks: ['sass', ...some other tasks like cssmin..., 'newer:copy']
}
},
sass: {
dist: {
files: [
...sass to css
]
}
},
copy: {
css: {
....
}
}
Also you can be interested in task like grunt-changed. The task configures another task to run with src files that have been changed. For more information please check the page grunt-changed

Keeping LESS sourceMaps for minified css with cssmin

My LESS files are compiled with grunt-contrib-less and corresponding grunt task with the following config:
module.exports = {
options: {
sourceMap: true,
sourceMapFilename: 'Content/styles/e-life.css.map'
},
compile: {
files: {
'Content/styles/e-life.css' : 'Content/styles/common.less'
}
}
}
Then I procced with cssmin for output css file. I get it minified, but I want to bind source maps from the previous step for the minified css.
module.exports = {
options: {
sourceMap: 'Content/styles/e-life.css.map'
},
all: {
files: {
'Content/styles/e-life.css': ['Content/styles/e-life.css']
}
}
}
The task fails if I mention source map path in options.sourceMap. I see the following in css-clean docs:
sourceMap - exposes source map under sourceMap property, e.g. new CleanCSS().minify(source).sourceMap (default is false) If input styles are a product of CSS preprocessor (Less, Sass) an input source map can be passed as a string.
But i can not understand how to pass this string to the task. Is it even possible? How can I do this?
grunt-contrib-cssmin does NOT let you chain sourcemaps.
Its sourceMap option is true/false only, and will generate a map from the minified css to the original css, not to the original Less, sorry.
Considering that source mapping is useful mainly for debugging, I would suggest:
do not use cssmin in your development environment, that way you get mapping from css to your Less files if needed.
use cssmin without mapping for production.
You could also avoid the Grunt cssmin task and use the Less compression with compress option.
module.exports = {
options: {
compress: true,
sourceMap: true,
sourceMapFilename: 'Content/styles/e-life.css.map'
},
compile: {
files: {
'Content/styles/e-life.css' : 'Content/styles/common.less'
}
}
}
https://github.com/gruntjs/grunt-contrib-less#compress

How to set CSS Source Map output destination when grunt-contrib-less is used

I am using grunt-contrib-less for compiling less files.
I have grunt locally installed at root of project folder.
The css files are located at qa1/avinash/html5/phase1/css/ path from root of project folder.
So this is the path i am specifying for cwd (current working directory), src and dest parameters of the grunt-less task. there are no issues in compilation of css and source map.
The only issue i face is that the source map is generated in the same folder of gruntfile. but my generated css is at the dest path i specified. since the css and source map are at different locations i have to manually edit the less path references in source map and bring it to the generated css directory. or use sourceMapURL to specify the source map location ../../../../../style.css.map(backwards). Both ways are not convenient.
So can anyone help me how to specify the source map output destination path like we specify for destination path for generated css something like
sourceMapDest: 'qa1/avinash/html5/phase1/css/'
--
currently used Gruntfile.js:
module.exports = function(grunt) {
grunt.initConfig({
less: {
options: {
sourceMap:true,
sourceMapFilename: "style.css.map",
sourceMapURL: '../../../../../style.css.map'
},
src: {
// no need for files, the config below should work
expand: true,
cwd: "qa1/avinash/html5/phase1/css/",
src: "style.less",
dest: "qa1/avinash/html5/phase1/css/",
ext: ".css"
}
},
watch: {
js: {
files: ['qa1/avinash/html5/phase1/css/'],
tasks: ['default'],
}
}
});
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['less']);
};
The sourceMapFilename option may include a path part as well.
I.e. just change it to:
sourceMapFilename: "qa1/avinash/html5/phase1/css/style.css.map"

Why is it recommended to use concat then uglify when the latter can do both?

I keep seeing the recommendation for making JS files ready for production to be concat then uglify.
For example here, in on of Yeoman's grunt tasks.
By default the flow is: concat -> uglifyjs.
Considering UglifyJS can do both concatenation and minification, why would you ever need both at the same time?
Thanks.
Running a basic test to see if there is a performance difference between executing concat and then uglify vs. just uglify.
package.json
{
"name": "grunt-concat-vs-uglify",
"version": "0.0.1",
"description": "A basic test to see if we can ditch concat and use only uglify for JS files.",
"devDependencies": {
"grunt": "^0.4.5",
"grunt-contrib-concat": "^0.5.0",
"grunt-contrib-uglify": "^0.6.0",
"load-grunt-tasks": "^1.0.0",
"time-grunt": "^1.0.0"
}
}
Gruntfile.js
module.exports = function (grunt) {
// Display the elapsed execution time of grunt tasks
require('time-grunt')(grunt);
// Load all grunt-* packages from package.json
require('load-grunt-tasks')(grunt);
grunt.initConfig({
paths: {
src: {
js: 'src/**/*.js'
},
dest: {
js: 'dist/main.js',
jsMin: 'dist/main.min.js'
}
},
concat: {
js: {
options: {
separator: ';'
},
src: '<%= paths.src.js %>',
dest: '<%= paths.dest.js %>'
}
},
uglify: {
options: {
compress: true,
mangle: true,
sourceMap: true
},
target: {
src: '<%= paths.src.js %>',
dest: '<%= paths.dest.jsMin %>'
}
}
});
grunt.registerTask('default', 'concat vs. uglify', function (concat) {
// grunt default:true
if (concat) {
// Update the uglify dest to be the result of concat
var dest = grunt.config('concat.js.dest');
grunt.config('uglify.target.src', dest);
grunt.task.run('concat');
}
// grunt default
grunt.task.run('uglify');
});
};
In src, I've put a bunch of JS files, including the uncompressed source of jQuery, copied several times, spread around into subfolders. Much more than what a normal site/app usually has.
Turns out the time it takes to concat and compress all of these files is essentially the same in both scenarios.
Except when using the sourceMap: true option on concat as well (see below).
On my computer:
grunt default : 6.2s (just uglify)
grunt default:true : 6s (concat and uglify)
It's worth noting that the resulting main.min.js is the same in both cases.
Also, uglify automatically takes care of using the proper separator when combining the files.
The only case where it does matter is when adding sourceMap: true to the concat options.
This creates a main.js.map file next to main.js, and results in:
grunt default : 6.2s (just uglify)
grunt default:true : 13s (concat and uglify)
But if the production site loads only the min version, this option is useless.
I did found a major disadvantage with using concat before uglify.
When an error occurs in one of the JS files, the sourcemap will link to the concatenated main.js file and not the original file. Whereas when uglify does the whole work, it will link to the original file.
Update:
We can add 2 more options to uglify that will link the uglify sourcemap to concat sourcemap, thus handling the "disadvantage" I mentioned above.
uglify: {
options: {
compress: true,
mangle: true,
sourceMap: true,
sourceMapIncludeSources: true,
sourceMapIn: '<%= paths.dest.js %>.map',
},
target: {
src: '<%= paths.src.js %>',
dest: '<%= paths.dest.jsMin %>'
}
}
But it seems highly unnecessary.
Conclusion
I think it's safe to conclude that we can ditch concat for JS files if we're using uglify, and use it for other purposes, when needed.
In the example you mention, which I'm quoting below, the files are first concatenated with concat and then uglified/minified by uglify:
{
concat: {
'.tmp/concat/js/app.js': [
'app/js/app.js',
'app/js/controllers/thing-controller.js',
'app/js/models/thing-model.js',
'app/js/views/thing-view.js'
]
},
uglifyjs: {
'dist/js/app.js': ['.tmp/concat/js/app.js']
}
}
The same could be achieved with:
{
uglifyjs: {
'dist/js/app.js': [
'app/js/app.js',
'app/js/controllers/thing-controller.js',
'app/js/models/thing-model.js',
'app/js/views/thing-view.js'
]
}
}
Typically, the task clean would then run after tasks that write to a temporary folder (in this example concat) and delete whatever content is in that folder. Some people also like to run clean before tasks like compass, to delete things like randomly named image sprites (which are newly generated every time the task runs). This would keep wheels turning even for the most paranoid.
This is all a matter of preference and workflow, as is with when to run jshint. Some people like to run it before the compilation, others prefer to run it on compiled files.
Complex projects with an incredible amount of JavaScript files - or with a increasingly broad number of peers & contributors, might choose to concatenate files outside uglify just to keep things more readable and maintainable. I think this was the reasoning behind Yeoman's choice of transformation flow.
uglify can be notoriously slow depending of the project's configuration, so there might be some small gain in concatenating it with concat first - but that would have to be confirmed.
concat also supports separators, which uglify doesn't as far as README.md files are concerned.
concat: {
options: {
separator: ';',
}
}

Expand not working in grunt-contrib-less task for dynamic selection

I've been playing with Grunt and one of the things I wanted to use it for was to compile my LESS files, but for some reason the expand: true (I commented everything out from the bottom up and it stopped throwing the err after commenting out expand) in the less:mini task is causing this error: Warning: Object true has no method 'indexOf' Use --force to continue. Does anyone know why this is happening? I can dynamically build the file object in grunt-contrib-copy no problem, and expand is required for the other options to work.
less: { // Set up to detect files dynamically versus statically
mini: {
options: {
cleancss: true, // minify
report: 'min' // minification results
},
files: {
expand: true, // set to true to enable options following options:
cwd: "dev/less/", // all sources relative to this path
src: "*.less", // source folder patterns to match, relative to cwd
dest: "dev/css/", // destination folder path prefix
ext: ".css", // replace any existing extension with this value in dest folder
flatten: true // flatten folder structure to single level
}
}
}
Thanks
files is intended to be used as an array or src-dest mappings. Grunt is interpreting the above properties within less.mini.files as src-dest mappings. See: http://gruntjs.com/configuring-tasks#files-object-format
You don't need to nest properties within files if you're not using that format. Modify your config to:
less: { // Set up to detect files dynamically versus statically
mini: {
options: {
cleancss: true, // minify
report: 'min' // minification results
},
expand: true, // set to true to enable options following options:
cwd: "dev/less/", // all sources relative to this path
src: "*.less", // source folder patterns to match, relative to cwd
dest: "dev/css/", // destination folder path prefix
ext: ".css", // replace any existing extension with this value in dest folder
flatten: true // flatten folder structure to single level
}
}

Resources