LoginSignup
4
3

More than 3 years have passed since last update.

Cordova で config.xml を動的に書き換えるテクニック

Last updated at Posted at 2019-07-02

Cordovaを使って、アプリ名 + .dev等の環境切り替えを行いたいと考えてしらべた内容を書いて置きます。今回は、firebaseを利用していたため、google-services.jsonから取得しましたが、適当なjsonファイルに定義しておいて使うことも可能です。

config.xml
...
<hook src="cordova-config.js" type="before_prepare" />
...

事前に cordova を npm install しておく必要あります。 

$ npm install cordova --save-dev

config.xmlと同じ階層で 実行したいJSを作成します。
google-services.jsonをパースして、IDを取得して置き換えをしています。

cordova-config.js
#!/usr/bin/env node
// NOTE: config.xmlを環境切り分け
// google-services.json から共通のIDを取得する
const google = require("./google-services.json" );
const lib = require('cordova').cordova_lib;
const config = new lib.configparser(__dirname + '/config.xml');

// NOTE: packageName、bundle IDを書き換える
config.doc._root.attrib.id = google.client[0].client_info.android_client_info.package_name;

// NOTE: CFBundleDisplayNameを書き換える
// 末尾を取得する
const env = google.client[0].client_info.android_client_info.package_name.split('.')[3];
for (let index in config.doc.find('platform')._children) {
  if (config.doc.find('platform')._children[index].attrib.parent === 'CFBundleDisplayName') {
    config.doc.find('platform')._children[index]._children[0].text = 'sample' + (env ? ('.' + env) : '');
  }
}
config.write();

あとは、prepareを実行されるタイミングで置き換えがされます。

$ cordova prepare

フックガイド

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3