Grunt - Queueing a task to run after a previous task completes - javascript

I looked at the official Grunt documentation for creating tasks here
http://gruntjs.com/creating-tasks
I have two tasks that I want to do, but the second one cannot run until after the first one completes. That's because the second task takes the output from the first task and uses it to create new output.
To break it down
My project involves Bootstrap, so it has a lot of unused code. My first objective is to remove the unused code with uncss. I would then take the output from this new css file and minify it with cssmin.
Here was the exact example from gruntjs
grunt.registerTask('foo', 'My "foo" task.', function() {
// Enqueue "bar" and "baz" tasks, to run after "foo" finishes, in-order.
grunt.task.run('bar', 'baz');
// Or:
grunt.task.run(['bar', 'baz']);
});
I tried to apply this to my code here
grunt.registerTask('default', 'uncss', function() {
grunt.task.run('cssmin');
});
This means that when grunt is entered, the default is to run the uncss task first, wait for it to complete, then run the cssmin task. However I got this output
Running "default" task
Running "cssmin:css" (cssmin) task
1 file created. 3.38kb -> 2.27kb
Done, without errors
Here is my initConfig
uncss: {
dist: {
files: {
'directory/assets/stylesheets/tidy.css': ['directory/*.html', 'directory/views/*.html']
}
}
},
cssmin: {
css: {
files: {
'directory/assets/stylesheets/styles.min.css': ['directory/assets/stylesheets/styles.css']
}
}
}
In other words, I have two stylesheets in my folder. One contains the custom styles I created, and another contains Bootstrap minified. By running uncss, I will get a new css file named tidy.css.
The cssmin task is supposed to look for this tidy.css file and minify it resulting in a new styles.min.css file.
I can get this to work, but I have to manually run one task and then run another one. How can I automate this to have them run in sequence

first, best practice is to use npm package to load all tasks automatically:
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
here are two grunt tasks:
one: {
wake up...
},
two: {
dress up...
},
and here is how you run one after the other
grunt.registerTask('oneThenOther', [
'one',
'two'
]);

You're close. When registering your alias task pass an array of tasks in the sequence you desire instead of a single task.
grunt.registerTask('default', ['uncss', 'cssmin']);
Alternatively, the sequence can be specified via the CLI:
> grunt uncss cssmin

It turns out part of the problem was I was specifying the wrong file under cssmin.
Changing my cssmin config to
cssmin: {
css: {
files: {
'directory/assets/stylesheets/styles.min.css': ['directory/assets/stylesheets/tidy.css']
}
}
}
and then registering the tasks in an array solved it
grunt.registerTask('default', ['uncss', 'cssmin']);
Note that the tasks must be specified in that order.

Related

Add a condition to run a gulp watch

I have a gulp watch task as following:
gulp.task("watch", () => {
const watch = {
'dev': [src_folder + '**/*.njk', src_js_folder + '**/*.js'],
'css': [src_sass_folder + '**/*.scss']
}
gulp.watch(watch.dev, gulp.series("dev")).on("change", browserSync.reload);
gulp.watch(watch.css, gulp.series("sass"));
});
gulp.task("dev", gulp.series("merge-json", "nunjucks", "sass", "js"));
So when there's any changes on *.sass files the sass task will run, and when there's changes on *.js and/or *.njk files the task dev will run.
The problem I'm having is when there are changes on *.sass, *.js and/or *.njk at the same time, the sass task will run twice in this case.
How can I skip the gulp.watch(watch.css, gulp.series("sass")); when the gulp.watch(watch.dev, gulp.series("dev")).on("change", browserSync.reload); is already run.
Problem
The double execution of the sass task when running the watch task occurs because in the code you have shared you are effectively defining the sass task to run twice.
gulp.task("watch", () => {
const watch = {
'dev': [src_folder + '**/*.njk', src_js_folder + '**/*.js'],
'css': [src_sass_folder + '**/*.scss']
}
// 1st execution > The `dev` task is defined into the `gulp.series()` as part
// of the combined tasks to run for this watcher, and, as `dev` contains the
// `sass` task in it this will run it the first time.
gulp.watch(watch.dev, gulp.series("dev")).on("change", browserSync.reload);
// 2nd execution > This watcher have the `sass` task defined into the
// `gulp.series()` as part of the combined tasks to run, this will run
// the second time
gulp.watch(watch.css, gulp.series("sass"));
});
// The `dev` task contains the`sass` task into the `gulp.series()` as part
// of the combined tasks to run
gulp.task("dev", gulp.series("merge-json", "nunjucks", "sass", "js"));
Therefore, every time you run gulp dev the sass task will be executed only once, and every time you run gulp watch the sass task will be executed twice.
Solution
To solve this problem you could perhaps reorder the executions in a slightly different way. Here are some ideas of what some possible solutions might look like.
- Possible Solution 1
const paths = {
njk: src_folder + '**/*.njk',
js: src_js_folder + '**/*.js',
sass: src_sass_folder + '**/*.scss'
}
gulp.task("watch", () => {
gulp.watch([
paths.njk,
paths.js,
paths.sass
],
gulp.series("dev")
).on("change", browserSync.reload);
});
gulp.task("dev", gulp.series("merge-json", "nunjucks", "sass", "js"));
In this example, we define the sass task as part of the combined tasks to run defined within the gulp.series for the dev task. This will allow us to run gulp dev and execute all those tasks only once. It will also allow us to run gulp watch and execute the tasks defined for the dev task only once each time the files defined in paths are updated.
- Possible Solution 2
const paths = {
njk: src_folder + '**/*.njk',
js: src_js_folder + '**/*.js',
sass: src_sass_folder + '**/*.scss'
}
gulp.task("watch", () => {
gulp.watch([
paths.njk,
paths.js,
],
gulp.series("dev")
).on("change", browserSync.reload);
gulp.watch(paths.sass, gulp.series("sass");
});
gulp.task("dev", gulp.series("merge-json", "nunjucks", "js"));
gulp.task("another_extra_task", gulp.series("dev", "sass"));
In this example, we removed the sass task from the combined tasks to run for the dev task, also, we defined the another_extra_task task where we are combining the dev and sass tasks. This will allow us to run gulp another_extra_task and execute all the combined tasks defined for dev and the sass task, but also, it will allow us to run gulp watch without repeating the execution of the sass task since in the first watcher we execute the dev task where the sass task isn't defined anymore and we just execute it with the second watcher.
Conclusion
Since the definition of the tasks depends on each particular use case, I recommend you try to reorder the execution of them in a more granular way. See the following reference which explains how to avoid duplicating tasks https://gulpjs.com/docs/en/api/series#avoid-duplicating-tasks
I hope these possible solutions help you to understand the problem you are having in the code you have shared!
Assuming this is due to rapid file changes, it may help to set the watch delay option:
gulp.watch(watch.dev, { delay: 500 }, gulp.series("dev"))
If that does not help, you may need to figure out a way to de-bounce the events. There's an old package called gulp-debounce which seems to achieve that, but is unmaintained and so is likely incompatible, but viewing its source may grant some insights.

How to make couple of minified files from different js files using grunt

I am new to grunt and task runners in JS, so this might seem a simple question but I have been unable to find exact working answer.
I have :
concat: {
options: {
// define a string to put between each file in the concatenated output
separator: '\n\n'
},
dist: {
// the files to concatenate
src: ['scripts/app.js', 'scripts/constant.js'
],
// the location of the resulting JS file
dest: 'scripts/custom.js'
}
},
This task collects all my custom file together. What I want is to do similar thing for all my vendors file. Finally I should end up with two js only custom.js having my concatenated-minified code and vendor.js having concatenated-minfied libraries.
How do I write grunt configuration for this. Do I need to make two different tasks. If I write the above code twice with different input files, it seems to run the last code.
grunt-contrib-concat can be configured to utilize multiple-targets.
For further documentation on this subject refer to multi-tasks and Task Configuration and Targets in the grunt documentation.
Gruntfile.js
For your scenario you need to configure your concat task similar to this (Note: the new custom and vendor targets):
module.exports = function(grunt) {
grunt.initConfig({
concat: {
options: {
separator: '\n\n'
},
custom: {
src: ['scripts/app.js', 'scripts/constant.js'],
dest: 'scripts/output/custom.js'
},
vendor: {
// Modify the src and dest paths as required...
src: ['scripts/vendor/foo.js', 'scripts/vendor/baz.js'],
dest: 'scripts/output/vendor.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('concatenate', [
'concat:custom', // <-- Targets in a task are called using a colon separator.
'concat:vendor'
]);
};
Running concat
Using the example gist provided above you can run the concat task via the CLI by typing the following command:
$ grunt concatenate
Configuring Options
If you require different configuration options for both the custom and vendor targets you will need to move the options object inside their respective targets. As explained here.
Note: Using the example gist provided the options specified will apply to both targets.

Grunt watch for tasks instead for files?

I`m new to Grunt and I saw a few tutorials about watch plugin. The example:
watch:{
sass:{
files: 'sass/*.scss',
tasks: ['sass','cssmin']
}
}
My question is why do I need to watch about another plungin like "sass" instead of watching the actual file(s) 'sass/*.scss'?
I don`t understand, it is not logical to watch a plugin/task, rather than a file.
Why I can`t call like this:
watch:{
files: 'sass/*.scss',
tasks: ['sass','cssmin']
}
?
And what if I want to also watch about my js file? Do I need to put it also in the files of the sass tasks? It does not make sense to have js files into sass task...
You're by no means watching a plugin. Suppose you have another plugin less, which you want to work on a different set of files. How will you do it?
watch {
sass: ...
less: ...
uglify: ...
}
Even if you put js files with sass (ignoring that it is horrible practice), when grunt calls sass on that file, nothing will happen.
As an example
module.exports = function (grunt) {
grunt.initConfig({
jshint: {
// ...
},
uglify: {
// ...
},
sass: {
// ...
},
foo: {
// ...
},
watch: {
javascript: {
files: 'javascripts/*/**.js',
tasks: ['jshint', 'uglify']
},
sass: {
files: 'sass/*/**.scss',
tasks: ['sass', 'foo']
}
}
});
// ...
};
There are different watchers for js, like uglify.
It's not that you're "watching" that plugin, it's that you're watching a set of files and running tasks when the files changes. the tasks specification is where you specify what tasks you need. So in this case you would run the sass and cssmin tasks.
The watch plugin watches files matching the pattern specified by files section. Whenever any of the matching files are changed, the tasks mentioned in tasks is executed.
For example, let us consider the watch task in your question
watch:{
sass:{
files: 'sass/*.scss',
tasks: ['sass','cssmin']
}
}
Here, sass is just a name given to the operation. It can be anything; but since the operation compiles Saas files, the operation is named saas.
Whenever any scss file in sass directory is changed, the operation saas is triggered, executing the saas and cssmin tasks, which should be defined earlier.
References:
Getting Started - Grunt: The JavaScript Task Runner

grunt and qunit - running a single test

I already have grunt-contrib-qunit set up. My Gruntfile.js includes something like this
qunit: { files: ['test/*.html'] }
Now I can run grunt qunit and all my tests run.
Question: how can I run just one single test without running all of them? Is there a way I can overload the value of files from the command line?
You definitely need to look into grunt-contrib-qunit and grunt-contrib-connect (https://github.com/gruntjs/grunt-contrib-qunit and https://github.com/gruntjs/grunt-contrib-connect) as the tandem will provide you with a headless phantom and a local webserver.
UPDATE - as for running just one specific test, you could write something like this, listing your tests as separate targets for your qunit task:
grunt.initConfig({
qunit: {
justSomething: ['test/justsomething.html'],
justSomethingElse: ['test/justsomethingelse.html'],
all: ['test/*.html']
}
});
Then you can call grunt qunit:justSomething, or grunt qunit:all - this is not specific to qunit, though - see http://gruntjs.com/configuring-tasks
Now, if you would really like to use the target to specify a test name, you would go with something like:
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.initConfig({
qunit: {
all: ['test/**/*.html']
}
});
grunt.task.registerTask('foo', 'A sample task that run one test.', function(testname) {
if(!!testname)
grunt.config('qunit.all', ['test/' + testname + '.html']);
grunt.task.run('qunit:all');
});
}
Then call grunt foo:testname.
Yet again, this is not specific to qunit - but rather grunt task writing.
Hope that (finally) helps.

How to disable a task in Grunt?

When grunt.loadNpmTasks is used, a grunt task is automatically available to the command line. It can be useful, but sometimes, I would like this task to be private, so it can be used whithin the Grunt file but not available to the command line.
Here is a contrived example. If I do :
module.exports = function(grunt) {
grunt.initConfig({
clean: {
test: ['test'],
release: ['release']
},
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('build', 'Build the project.', function() {
console.log("building project");
});
grunt.registerTask('release', ['clean:release', 'build']);
};
... I can use the following command :
$ grunt release
However, this one is also available, and both clean:release and clean:test will be executed:
$ grunt clean
I do not want that. I want to control what can be called from the command line, since I may not have foreseen some undesirable effects if the user directly calls some tasks or subtasks.
I thought about registering a new clean task to supersedes the main one, and then choose what to call when clean is invoked (or to call nothing at all), but it does not work well since it cannot call the original clean task:
grunt.registerTask('clean', ['clean:release']);
Use grunt.task.renameTask
var ticks = +new Date();
var clean = 'clean-' + ticks;
grunt.task.renameTask('clean', clean);
grunt.registerTask('release', [clean + ':release', 'build']);
grunt.config.set(clean, grunt.config.get('clean'));
Copying the configuration over is important if you want to preserve the targets configuration

Categories

Resources