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) {

3) List necessary plugins in ./package.json:
  "cordovaPlugins": [

4) Define hook in ./config.xml:
<widget id="com.ionicframework.myapp" version="0.0.1" xmlns="" xmlns:cdv="">
  <hook type="before_build" src="scripts/010_install_plugins.js" />

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