Skip to content

Hooks and Cordova CLI

Hooks are scripts that you can run before and after each stage of the Cordova CLI lifecycle. They live in a projecthome/.cordova/hooks/before_xxx (or after_xxx) where xxx is the project lifecycle stage (prepare, build, etc).

They are somewhat documented here, and here’s an example you can “borrow” from. As we’ll see in the next few posts, they are a lifesaver at dealing with some of the current deficiencies of Cordova CLI.

But to start with, all you need to know is that hooks are chunks of code that are passed the project base directory as the first argument (and therefore available via var rootdir = process.argv[2]; for node, or $1 for shell scripts). These chunks can be any kind of executable code (shell/node/perl/python/compiled c, etc). All I focus on here are project specific hooks–I don’t know how module hooks would work.

I have typically used hooks to move and manipulate files and used node (though you can use any scripting language) and am a node newbie–therefore stackoverflow and the node filesystem API docs were my friends.

Each hook is executed in alphabetical order within the before_ or after_ directory. A good idea is to name each hook to make the order explict:

  • 001_script
  • 010_script
  • 020_script
  • 120_script

executes scripts in the order you would expect, where:

  • 1_script
  • 10_script
  • 20_script
  • 120_script

does not.

In addition, if you write node scripts, consider using the synchronous versions of the file manipulation commands. While the default node commands (to move a file, say) are asynchronous, and therefore fast, for a build environment I have seen confusing results if I didn’t make everything synchronous. If you need the build process to be faster, then consider going async, but know what you are doing.

In the next post, I will discuss configuration for different environments.

Subscribe to my infrequent Cordova newsletter

2 thoughts on “Hooks and Cordova CLI

  1. Bas says:

    Is is possible in Windows 7 to use hooks written in NodeJS???

  2. moore says:

    I believe so, but haven’t done this myself. If you are using the cordova CLI on Windows 7, nodejs is correctly installed.

    You might want to check out the hooks sample chapter of my ebook on cordova CLI for some tips about node.js hooks: http://leanpub.com/developingwithcordovacli/read

Comments are closed.