Gulp hook before 'cordova build xxx'
Asked Answered
P

3

6

I have my gulpfile.js with some tasks and I want to execute one task when I do cordova build

I created a before_build folder inside of the hooks folder with a simple console.log("a")in a js file.

But whe I run for example cordova build android it says 'console' is undefined, I have to do something else to run Javascript? I couldn´t find more info.

Thanks!

EDIT:

I added #!/usr/bin/env node at the top of my .js file and the console.log works but now I want to do gulp myTask and is throwing to me gulp is not defined

Perionychium answered 3/2, 2015 at 20:43 Comment(0)
J
8

You can run it without leaving Node by pasting this code into the file before_build/010_compile_css.js:

#!/usr/bin/env node

var gulp = require('gulp');
var path  = require('path');

var rootdir = process.argv[2];
var gulpfile = path.join(rootdir, 'gulpfile.js');

process.stdout.write('Compiling SCSS');

require(gulpfile);

//interaction
gulp.start('scss');
James answered 11/2, 2015 at 18:18 Comment(3)
Will gulp.start() complete synchronously as Cordova hooks require?Entozoon
I found that gulp.start() is deprecated and scheduled to be removed: github.com/gulpjs/gulp/issues/505 .. Though that was a year ago!Entozoon
Latest Cordova no longer recommending using hooks folder, it will be deprecated soon. Please use JS method instead as per suggest by @David DouglasCartel
P
5

I found I had to use __dirname to require the 'gulpfile.js' file.

#!/usr/bin/env node

module.exports = function(context) {
  var Q = context.requireCordovaModule('q');
  var deferral = new Q.defer();

  var path = require('path'),
      gulp = require('gulp'),
      gulpfile = path.join(__dirname, 'gulpfile');
  require(gulpfile);

  gulp.start('myTask').once('task_stop', function(){
      console.log('myTask done');
      deferral.resolve();
  });

  return deferral.promise;
}

NB: The 'gulpfile.js' and 'hook.js' are in same directory here. You can set custom path to hook js file in Cordova's config.xml file:

<hook type="before_build" src="app/hook.js" />
Pinkerton answered 2/12, 2015 at 16:17 Comment(1)
Also beware that Cordova hook scripts act from the root project directory so you may run into file path issues if your gulpfile.js operates from within a sub-directory.Pinkerton
P
3

Finally I could run the command, here is my .js file inside hooks/before_build

#!/usr/bin/env node
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("gulp", puts);
Perionychium answered 4/2, 2015 at 14:20 Comment(2)
not the best solution since you're creating a new process from node to run another node script (gulp).Camper
@Camper so, what do you think it's a better solution?Perionychium

© 2022 - 2024 — McMap. All rights reserved.