Hooks now give you, as of cordova CLI 3.3.1-0.4.2, much more information about the environment you were executing in.
Before, if I had platform specific code, I needed to check at runtime:
App.config.flurryid = ""; if (window.device && window.device.platform) { if (window.device.platform == "Android") { App.config.flurryid = /*REP*/ 'notreallyanandroidflurryid' /*REP*/ ; } if (window.device.platform == "iOS") { App.config.flurryid = /*REP*/ 'notreallyaniosflurryidxxx' /*REP*/ ; } }
Now, you can inject platform specific code at build time, via hooks. The runtime code is simplified to
App.config.flurryid = /*REP*/ 'myflurryid' /*REP*/;
and you just replace 'myflurryid'
with the appropriate value from your configuration file (more on platform specific configuration files).
From the readme in the hooks directory:
All scripts are run from the project’s root directory and have the root directory passes as the first argument. All other options are passed to the script using environment variables:
* CORDOVA_VERSION – The version of the Cordova-CLI.
* CORDOVA_PLATFORMS – Comma separated list of platforms that the command applies to (e.g.: android, ios).
* CORDOVA_PLUGINS – Comma separated list of plugin IDs that the command applies to (e.g.: org.apache.cordova.file, org.apache.cordova.file-transfer)
* CORDOVA_HOOK – Path to the hook that is being executed.
* CORDOVA_CMDLINE – The exact command-line arguments passed to cordova (e.g.: cordova run ios –emulate)
Here’s a sample plugin which you can put in your hooks/before_prepare
directory. If you do this and then run cordova -d prepare
you can see the values for all the variables.
#!/usr/bin/env node console.log("process.env.CORDOVA_VERSION: "+process.env.CORDOVA_VERSION); console.log("process.env.CORDOVA_PLATFORMS: "+process.env.CORDOVA_PLATFORMS); console.log("process.env.CORDOVA_PLUGINS: "+process.env.CORDOVA_PLUGINS); console.log("process.env.CORDOVA_HOOK: "+process.env.CORDOVA_HOOK); console.log("process.env.CORDOVA_CMDLINE: "+process.env.CORDOVA_CMDLINE);
Here’s the output for a test project.
Executing hook ""/home/mooreds/git/testproject3/hooks/before_prepare/test.js" "/home/mooreds/git/testproject3"" process.env.CORDOVA_VERSION: 3.3.1-0.4.2 process.env.CORDOVA_PLATFORMS: android process.env.CORDOVA_PLUGINS: process.env.CORDOVA_HOOK: /home/mooreds/git/testproject3/hooks/before_prepare/test.js process.env.CORDOVA_CMDLINE: node /usr/local/bin/cordova -d prepare
Note that if you are using this for platform specific code, you will want to run the commands separately: cordova build android
and cordova build ios
. If you just run cordova build
and you have both ios and android platforms installed, the process.env.CORDOVA_PLATFORMS
variable will be android,ios
, and your code won’t be able to differentiate between them.
If you want to know about more Cordova CLI changes, check out “3 Cordova CLI Changes You Should Know About” which covers version 3.3.1-0.3.1.