Using output of one task as an input for another - gruntjs

I have an html file that contains references to js files. I want to parse it extract a list of referenced js files and feed contrib-concat or any other task with them.
Is there any convenient way to use output of one grunt task as an input for another?

Use grunt.config. Here is an example:
grunt.initConfig({
concat: {
js: {
src: ['default/concat/files/*'],
dest: ['dist/javascript.js'],
},
},
});
grunt.registerTask('extractjs', function() {
/* Do the js extraction */
// Overwrite the concat.js.src with your extracted files.
grunt.config(['concat', 'js', 'src'], extractedFiles);
});
So now when you run grunt extractjs concat it will extract the js and then concat the extracted js files. Check out this task: https://github.com/cgross/grunt-dom-munger as he is working on a similar goal. Here is a grunt issue with more examples as well: https://github.com/gruntjs/grunt/issues/747

Related

How do I generate sourcemaps for Uglified files using Grunt?

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

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

With Grunt, how can I compile all *.less files, if I have global mixins and constants?

I want to organize my HTML, JS, and LESS by module. I'm already using Grunt to compile *.js and *.html from my source folders.
So I configured grunt as follows:
grunt.initConfig({
less: {
ALL: {
files: { 'compiled.css': '**/*.less' }
}
}
}
But this runs into a major problem: constants and mixins from my /helper/*.less files are not accessible to other .less files.
It seems like grunt-contrib-less compiles each individual .less file, and then combines the output, but doesn't compile anything "globally".
The only solution I can think of is to create and maintain a master.less that #imports each individual .less file. But I'm trying to achieve an extremely modular build process, and I don't have to list any HTML or JS files, so I'm really hoping to find a *.less solution too!
Thanks to #seven-phases-max for the following answer!
less-plugin-glob
Allows you to use wildcards in #import statements! Works perfectly!
// master.less
#import "helpers/**/*.less";
#import "modules/**/*.less";
And all you need to add to your Grunt configuration is the plugins option:
// Gruntfile.js
grunt.initConfig({
less: {
'MASTER': {
src: 'master.less',
dest: 'master.css',
options: {
plugins: [ require('less-plugin-glob') ]
}
}
}
});
And, don't forget, npm install less-plugin-glob.
Here's one way to achieve an effortless development experience.
However, it requires a generated file and a custom task.
Auto-generate the master.less file
Create a task that generates master.less by writing an #import statement for each *.less file:
grunt.registerTask('generate-master-less', '', function() {
generateFileList({
srcCwd: 'modules',
src: '**/*.less',
dest: 'less/master.less',
header: '// THIS FILE IS AUTOMATICALLY GENERATED BY grunt generate-master-less\n',
footer: '// THIS FILE IS AUTOMATICALLY GENERATED BY grunt generate-master-less\n',
template: '#import "<%= filename %>";\n',
join: ''
});
});
function generateFileList(options) {
var _ = grunt.util._;
var files = grunt.file.expand({ cwd: options.srcCwd }, options.src);
var results = files.map(function (filename) {
return _.template(options.template, { 'filename': filename });
});
var result = options.header + results.join(options.join) + options.footer;
grunt.file.write(options.dest, result);
}
Then, use grunt-contrib-less to just build master.less.

Is it possible with Grunt to merge all js/css files in a specific folder in to one js/css file?

I'm new with Grunt and I wasn't able to find what I'm looking for.
I have this folder's structure configuration :
app/
public/
assets/
... some javascript/css libs like jQuery, Bootstrap, etc
css/
js/
img/
What I'd like to do is compress all the js files in public/assets/ into one assets.js file that would be in js/assets.js, and do the same for all the css files into assets.css in css/assets.css.
Moreover, I'd like those two assets.js/css file to be compressed.
A link to a solution or some start of a solution is all I need.
Thank you!
Firstly you need to concatenate your files and then run them through a minifier. Grunt has plenty of plugins that will do these things but some of the more popular ones are grunt-contrib-concat, grunt-contrib-uglify and grunt-contrib-cssmin.
These tasks have plenty of options available to taylor them to your needs but this should help you get started.
As sample configuration for the concat task would be something like:
grunt.initConfig({
concat: {
options: {
separator: ';',
},
js: {
src: ['public/assets/a.js', 'public/assets/b.js', 'public/assets/c.js'],
dest: 'public/js/assets.js',
},
js: {
src: ['public/assets/a.css', 'public/assets/b.css', 'public/assets/c.css'],
dest: 'public/css/assets.css',
},
},
});
Then for your minify js task:
uglify: {
js: {
files: {
'public/assets/js/assets.min.js': 'public/assets/js/assets.js'
}
}
}
And finally, css minify task:
cssmin: {
files: {
'public/assets/css/assets.min.css' : 'public/assets/css/assets.css'
}
}

Using grunt to concat js for multiple pages

I'm very new to grunt. As I was reading examples I wondered how should I handle next case. Lets assume I have this structure:
/pages/layout.php
/pages/index.php
/pages/contacts.php
Layout contains common js (like jquery/bootstrap) while contacts extends layout.php and adds some new js
So, layout uses
jquery.js
bootstrap.js
contacts.php
jquery.js
bootstrap.js
feedback.js
In articles I read the authors usually would create only one file, like frontend.js then uglify it. But if I have multiple js-plugins combination for each page, am I right that my concat configuration should look like:
module.exports = function(grunt) {
// I haven't tested this but that's the way I think it should look
// Common scripts which will be used on every page
var layout = ['/path/to/jquery.js', '/path/to/bootstrap.js'];
grunt.initConfig({
concat: {
options: {
separator: "\n"
},
layout: {
src: layout.concat(['/path/to/index.js']),
dest: '/path/to/result'
},
contacts: {
src: layout.concat(['/path/to/feedback.js']),
dest: '/path/to/result'
}
}
});
}
The config might get quite big, depending on how much pages (which use js) I have. Or there is another approach to do such thing?

Resources