I tried to run the watch task by grunt in node.js but it doesn't work for me (this is what I got):
$ grunt watch
warning: Maximum call stack size exceeded Use --force to continue.
This is the part of the watch task in the Gruntfile.js:
watch: {
less: {
files: 'src/less/*.less',
tasks: ['clean', 'recess', 'copy']
},
js: {
files: 'src/js/*.js',
tasks: ['clean', 'jshint', 'concat', 'uglify', 'copy']
},
theme: {
files: 'src/theme/**',
tasks: ['clean', 'recess', 'copy']
},
images: {
files: 'src/images/*',
tasks: ['clean', 'recess', 'copy']
}
}
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('watch', ['watch']);
u_mulder is correct; simply remove the unnecessary grunt.registerTask('watch', ['watch']) line from your code and you should be good to go.
Edit: This happens because you are registering a new task that calls itself. Adding a line like grunt.registerTask('watch', ['watch']); doesn't make sense because it is already defined for you. If this wasn't the case you would have to call grunt.registerTask for each and every task in your Gruntfile config.
In some cases it might make sense to alias the task with a different name. It would be called with the exact same configuration that you have specified, but aliasing it could save typing. For instance I like to register my available tasks plugin with the 'tasks' alias, so instead of typing grunt availabletasks I can type grunt tasks and that saves me some typing. In this instance you could do something like:
grunt.registerTask('w', ['watch']);
And you can then use grunt w as a shortcut for grunt watch.
Actually, deleting grunt.registerTask('watch', ['watch']) will sort you out.
But let me help you to understand what's happening under the hood.
With grunt.registerTask('watch', ['watch']), watch is calling itself, which generates an infinite loop.
When you delete it, it still works, cause watch is the default task of the package, which I guess is called at the very beggining of your file with grunt.loadNpmTasks('grunt-contrib-watch');. You can go further on doc here
However, it would be really handy to get your customization of the watch task to work as you want it to do. For this to happen, it would be probably better to do something like grunt.registerTask('watchfiles', ['watch']). With this you avoid the infinite loop and make your customization work.
And you would run the task like this $ grunt watchfiles and it would perform well.
Note that all the paths must be the right ones, otherwise, if a task has a wrong path specified, it will just not run.
Related
While seemingly the tasks execute in proper order (bump first and than ngconstant creating a config file based on package.json-s version property) i think they actually execute parallely, and ngconstant reads up the package.json before bump has written it.
Running "bump" task
md
>> Version bumped to 2.0.6 (in package.json)
Running "ngconstant:production" (ngconstant) task
Creating module config at app/scripts/config.js...OK
The resultung package.json has 2.0.6 as version while config.js has 2.0.5.
My ngconstant config simply uses
grunt.file.readJSON('package.json')
to read up the json.
So, basically the question is, how can i make sure that bump's write is finished, before reading up the json with ngconstant, and what actually causes the above?
EDIT: the original Gruntfile: https://github.com/dekztah/sc2/blob/18acaff22ab027000026311ac8215a51846786b8/Gruntfile.js
EDIT: the updated Gruntfile that solves the problem: https://github.com/dekztah/sc2/blob/e7985db6b95846c025ba0b615bf239c4f9c11e8f/Gruntfile.js
Probably your package.json file is stored in memory and is not updated before your run the next task.
An workaround would be to create a script in your file package.json as:
"scripts": {
"bumb-and-ngconstant": "grunt:bump && grunt:build"
}
As per grunt-ng-constant documentation:
Or if you want to calculate the constants value at runtime you can create a lazy evaluated method which should be used if you generate your json file during the build process.
grunt.initConfig({
ngconstant: {
options: {
dest: 'dist/module.js',
name: 'someModule'
},
dist: {
constants: function () {
return {
lazyConfig: grunt.file.readJSON('build/lazy-config.json')
};
}
}
},
})
This forces the json to be read while the task runs, instead of when grunt inits the ngconstant task.
My gulpfile.js looks as below. If I execute gulp watch, the copy task does not get executed on change of app.js. In fact, if I have the copy task alone, gulp watch will execute copy once and then exit. What am I doing wrong?
elixir(function (mix) {
mix.scripts(
[
'../../../bower_components/angular/angular.js'
]
).copy('resources/assets/js/app.js', 'public/js/app.js')
});
In order for Elixir to watch all the files inside the assets folder you need to instruct it where to look for additional resources. For that you simply need to use the registerWatcher method.
Unfortunately Laravel documentation leaves a lot to desire so this option is often overlooked because it's not properly documented.
elixir.config.registerWatcher("default", "resources/assets/**", null);
elixir(function (mix) {
mix.scripts(
[
'../../../bower_components/angular/angular.js'
]
).copy('resources/assets/js/app.js', 'public/js/app.js')
});
The story:
We have a team of testers working on automating end-to-end tests using protractor for our internal AngularJS application. Here is the task they usually run for "local" testing:
grunt.registerTask('e2e:local', [
'build:prod',
'connect:test',
'protractor:local'
]);
It runs the "build" task, starts a webserver and runs the e2e tests against the local build.
The build:prod task itself is defined as:
grunt.registerTask(
'build:prod', [
'clean',
'copy:all',
'copy:assets',
'wiredep',
'ngtemplates',
'useminPrepare',
'concat',
'ngAnnotate',
'autoprefixer',
'uglify',
'cssmin',
'copy:cssfix',
'usemin',
'copy:html',
'bowercopy',
'template:setProdVersion'
]
);
Here we have a lot of subtasks (it definitely could be improved, but this is how it looks now).
The problem:
Currently, it takes about 25 seconds for the build to complete. And, every time a person is running end-to-end tests, the build task is executed.
The question:
How can I run the build:prod task only if there are changes in src directory?
Note that the requirement here is to make it transparent for the testers who run the tests. I don't want them to remember when they need to perform a build and when not.
In other words, the process should be automated. The goal is to automatically detect if build is needed or not.
Note that ideally I would like to leave the build task as is, so that if it is invoked directly via grunt build:prod it would rebuild regardless of the datestamp of the previous build.
Thoughts and tries:
there is the closely related grunt-newer package, but, since we have a rather complicated build, having a clean task at the beginning, I'm not sure how to apply it in my case
what I was also thinking about is to, inside the e2e:local task, manually check the timestamps of the files inside dist and src and, based on that, decide if build:prod is needed to be invoked. I think this is what grunt-newer is doing internally
we started to use jit-grunt that helped to improve the performance
Here's an idea if you use git:
How about using something like grunt-gitinfo and using the last commit in HEAD as a base?
The idea is:
You create a new grunt task that checks for latest commit hash
You'd save this commit hash in a file that's added to gitignore (and is NOT in the clean folder, typically can be in root of repo)
Before saving to file, it'd check the value already in it (standard node fs module can do the read/write easily)
If the hash doesn't match, run build:prod task then save new commit hash
The testers build would depend on your new task instead of build:prod directly
Another option (still using git):
You can use something like grunt-githooks and create a git hook that runs after pull and calls the git build:prod, then you can remove it from the dependencies of the grunt task that testers run.
You might have another code to check for githook and install it if required though, which can be a one-time extra step for testers, or maybe baked into the grunt task they call.
I'm surprised noone has mentioned grunt-contrib-watch yet (it's in the gruntjs.com example file and I thought it was pretty commonly known!). From github: "Run predefined tasks whenever watched file patterns are added, changed or deleted." - heres a sample grunt file that would run your tasks any time any .js files are modified in src/ or in test/, or if the Gruntfile is modified.
var filesToWatch = ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'];
grunt.initConfig({
watch: {
files: filesToWatch,
tasks: ['build:prod',
'connect:test',
'protractor:local']
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
You have your developers open a terminal and run grunt watch before they start modifying files, and every time those files are modified the tasks will automatically be run (no more going back to the terminal to run grunt build:prod every time).
It's an excellent package and I suggest you check it out. -- github -- npmjs.org
npm install grunt-contrib-watch --save-dev
Not the answer your are looking for with grunt, but this will be easy with gulp.
var fs = require('fs');
var gulpif = require('gulp-if');
var sourceChanged = fs.statSync('build/directory').mtime > fs.statSync('source/directory').mtime;
gulp.task('build:prod', function() {
if (!sourceChanged) {
return false;
}
return gulp.src('./src/*.js')
.pipe(.... build ....)
.pipe(gulp.dest('./dist/'));
});
Here's how we've done some Git HEAD sha work for our build. We use it to determine which version is currently deployed to our production environment - but I'm quite certain you could rework it to return a boolean and trigger the build if truthy.
Gruntfile.js
function getHeadSha() {
var curr, match, next = 'HEAD';
var repoDir = process.env.GIT_REPO_DIR || path.join(__dirname, '..');
try {
do {
curr = grunt.file.read(path.join(repoDir, '.git', next)).trim();
match = curr.match(/^ref: (.+)$/);
next = match && match[1];
} while (next);
} catch(ex) {
curr = 'not-found';
}
return curr;
}
grunt.initConfig({
replace: {
applicationVersion: {
src: '<%= config.dist %>/index.html',
overwrite: true,
replacements: [{
from: '{{APPLICATION_VERSION}}',
to: getHeadSha
}]
}
}
});
grunt.registerTask('build', {
'replace:applicationVersion',
/** other tasks **/
});
grunt.registerTask('e2e:local', {
'check_if_we_should_build',
/** other tasks **/
});
index.html
<html data-version="{{APPLICATION_VERSION}}">
<!-- -->
</html>
There's also the git-info package which would simplify this whole process, we're looking at switching over to that ourselves.
edit; I just noticed #meligy already pointed you in the direction of git-info. credit where credit is due.
I am not sure if its helpful or not but same things we have done it in our project using GULP framework. We have written a watcher in the gulp that continuously check for the source change and run a quick function to build the project. Its a Protractor Test case.
gulp.task('dome', function () {
gulp.src(["maintest.js"])
.pipe(notify("Change Found , Executing Scripts."))
.pipe(protractor({
configFile: "conf.js",
args: ['--baseUrl', 'http://127.0.0.1:8000']
})).on('error', function (e) {
throw e
});
})
gulp.task('default', function () {
gulp.watch('./webpages/*.js', ['dome']);
gulp.watch('maintest.js', ['dome']);
gulp.watch('conf.js', ['dome']);
});
Link to repo.
I don't have experience in protractor, but conceptually I think this could work.
What I could suggest is to set an alias in your ~/.cshrc to run the build commands only if a diff command returns true.
#./cshrc
alias build_on_diff 'diff -r branch_dir_1 branch_dir_2\
if ( $status == 1 ) then\
build:prod\
endif'
Just replace the diff command with whatever git uses, and it should work provided it returns a 1 status for differences detected. We apply a similar method at my workplace to avoid rebuilding files that haven't changed.
Context
I have a few grunt tasks that I've already written, and I'd like to use them with a new project I'm writing in Sails.js.
With Sails.js, you can add additional grunt tasks by adding a JS file to the /tasks/register folder. Before we get to the file I've added, let's talk about the problem.
The Problem
Sails won't lift. Debugger shows:
debug: --------------------------------------------------------
error: ** Grunt :: An error occurred. **
error:
------------------------------------------------------------------------
ERROR
>> Unable to process task.
Warning: Required config property "clean.dev" missing.
The issue in question is obviously with grunt, so then I try grunt build (which automatically runs with sails lift):
Running "clean:dev" (clean) task
Verifying property clean.dev exists in config...ERROR
>> Unable to process task.
Warning: Required config property "clean.dev" missing. Use --force to continue.
From this, I've garnered that this is a path issue. Let's take a look at the file I've added.
/tasks/register/customTask.js
The task here loads load-grunt-config, which is the source of my problems:
module.exports = function(grunt) {
// measures the time each task takes
require('time-grunt')(grunt);
// This require statement below causes my issue
require('load-grunt-config')(grunt, {
config: '../../package.json',
scope: 'devDependencies',
overridePath: require('path').join(process.cwd(), '/asset-library/grunt')
});
grunt.registerTask('customTask', [
'newer:jshint',
'newer:qunit',
'newer:concat',
'newer:cssmin',
'newer:uglify'
]);
};
I had assumed that using overridePath instead of configPath would solve my issue, but alas, it's not quite that simple. Is there some way to make it so that I can use my own custom tasks folder with load-grunt-config like I've done in other projects, or is there some magic conditional I can wrap the require statement around?
I only need it to run with grunt customTask, and not run with grunt * (anything else).
Okay, this was actually pretty easy. All I had to do was change the grunt.registerTask call in my customTask.js file from this:
grunt.registerTask('customTask', [
'newer:jshint',
'newer:qunit',
'newer:concat',
'newer:cssmin',
'newer:uglify'
]);
to this:
grunt.registerTask('customTask', 'My custom tasks', function() {
// The require statement is only run with "grunt customTask" now!
require('load-grunt-config')(grunt, {
config: '../../package.json',
scope: 'devDependencies',
overridePath: require('path').join(process.cwd(), '/asset-library/grunt')
});
grunt.task.run([
'newer:jshint',
'newer:qunit',
'newer:concat',
'newer:cssmin',
'newer:uglify'
]);
});
In case it's not clear, I did have to move the require('load-grunt-config') call, so if you're copy + pasting, make sure to remove the require statement that's outside the grunt.registerTask call.
You can find more information about custom Grunt tasks here.
So here is my hypothetical config object for a hypothetical fooTask that does something (not relevant to question) to a bunch of JS files
grunt.initConfig({
fooTask: {
app1: 'app1/*.js',
app2: 'app2/*.js',
app3: 'app3/*.js'
}
});
As you can see, with this approach, I have to run fooTask 3 times with each app specified as a target:
grunt fooTask:app1
grunt fooTask:app2
grunt fooTask:app3
Needless to say this does not scale as either the number of apps increase or the number of such foo tasks increase as one has to C&P the same code over and over for each app.
So ideally what I would like to define is just one target with the name of the app passed in as a config variable
grunt.initConfig({
fooTask: {
dist: '<%=appName%>/*.js'
}
});
I would then like to call fooTask 3 times, one for each app, with the right app set as appName
var apps = ['app1', 'app2', 'app3'];
apps.forEach(function(app) {
var currAppName = app;
// Run fooTask but how do I specify the new currAppName config?
grunt.task.run('fooTask');
});
As from code above, I know I can run my fooTask using grunt.task.run but how do I set the appName config for my task?
Note that this question is similar to this other one that also does not have the right answer yet - Pass Grunt config options from task.run
Thanks a lot.
EDIT 2:
So nevermind the garbage below the first edit, leaving as example of what doesn't work. In my case it was really important to be able to set the value within a task at run-time so I settled on the file system. Perhaps it suits your needs.
grunt.initConfig({
someTask: {
someKey: fs.readFileSync('file.txt', { encoding: 'utf8' })
}
});
of course you can do the readFile outside of the task if you need a bunch of different app names.
EDIT:
Hmmm. I swear I had this working when I wrote this...but now it is not. Grunt just sees the extra arguments as additional unfound tasks.
I was trying to figure this out myself, finally a "duh" just moment happened - why not parse process.argv before grunt.initConfig?
module.exports = function(grunt) {
var sourcefile = process.argv[2] || 'default.js'; // <- this
grunt.initConfig({
uglify: {
main: {
src: sourcefile, // <- voila :)
dest: sourcefile.substring(0, sourcefile.length-3) + '.min.js'
}
}
});
grunt.loadNpmTasks('uglify');
grunt.registerTask('default', ['uglify']);
};
and use from command line:
grunt mykillerscript.js
I didn't even try to use grunt.option for the same reason that all the examples only showed directing which task is run, but I wouldn't be surprised if there is a more "grunt" way to do this.