Friday, November 18, 2016

ionic - auto install plugins on platform build

Hi there,

Today I will start my short series of posts about ionic, mobile framework for Android and iOS. Don't ask me how is it related to Python. I just needed to do some work for mobile.

One common task, that you need to do with ionic is to build your platform and install plugins. Let's choose Android as our platform.

To build android platform and install plugins you need to run commands like this:
cordova plugin add someplugin1
cordova plugin add someplugin2
ionic build android


But I would prefer to run only one command instead of several. This can also make life easier for other developers, they won't need to add plugins manually. In order do this, we can create hook for plugins installation which will be called during platform build. Let's do it below.

1) In the root of your ionic project, create file scripts/010_install_plugins.js:
mkdir -p scripts
touch scripts/010_install_plugins.js
chmod +x scripts/010_install_plugins.js

2) scripts/010_install_plugins.js:
#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var packageJSON = require('../package.json');

packageJSON.cordovaPlugins = packageJSON.cordovaPlugins || [];

packageJSON.cordovaPlugins.forEach(function(plugin) {

    process.stdout.write("ADDING plugin " + plugin)

    exec("cordova plugin add " + plugin, function (error, stdout, stderr) {
        process.stdout.write(stdout)
    });
});

3) List necessary plugins in ./package.json:
...
  "cordovaPlugins": [
    "cordova-plugin-device",
    "cordova-plugin-console",
    "cordova-plugin-whitelist",
    "cordova-plugin-splashscreen",
    "cordova-plugin-statusbar",
    "ionic-plugin-keyboard",
    "https://github.com/Initsogar/cordova-webintent.git"
  ],
...

4) Define hook in ./config.xml:
<widget id="com.ionicframework.myapp" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
...
  <hook type="before_build" src="scripts/010_install_plugins.js" />
...
</widget>


Now you can build your ionic platform with only one command, which will automatically add plugins for you:
ionic build android

No comments:

Post a Comment