ionicではangularのenvironmentsのような環境ごとに変数を切り替える機能がデフォルトではないので、調べた中で一番シンプルそうな方法で実装してみようと思います。
(ionic4では実装されるらしい。)
1. 各環境用のjsonファイルを作成する
.envフォルダを作成し、環境毎にjsonファイルを作成します。
.env/
production.json
staging.json
development.json
ファイルの中身は、以下のような内容にします。
{
"environment": "development",
"endpoints": {
"server1": "https://....",
"server2": "https://...."
}
}
2.Scriptを作成する
上記jsonファイルを読み込み、app.config.tsファイルを生成するためのスクリプト、./scripts/environment.js
を作成します。
#!/usr/bin/env node
var path = require('path');
var process = require('process');
var fs = require('fs');
class Environment {
constructor(args) {
args = JSON.parse(args).original;
const defaultEnv = 'development'; //Set default environment
let env;
if(args.includes('ionic:build')) {
let envFlags = args.filter((arg) => arg.includes("--env"));
env = (envFlags.length === 1) ? envFlags[0].substr(envFlags[0].indexOf("=") + 1) : defaultEnv;
} else {
let index = args.indexOf('--env');
env = (index > -1) ? args[index+1] : defaultEnv;
}
console.log(`Using environment config: ${env}`);
this.setEnvironment(env);
}
setEnvironment(env) {
let config;
try {
config = require(path.join('../', '.env', env + '.json'));
} catch(e) {
throw new Error(`The config file for this environment is missing (${e.message})`);
}
var wstream = fs.createWriteStream(path.resolve('./src/app/app.config.ts'));
wstream.write(`
import { InjectionToken } from "@angular/core"; //Use InjectionToken in Angular 4.x
export let APP_CONFIG = new InjectionToken<string>("app.config");
export const AppConfig = ${JSON.stringify(config)};
`);
wstream.end();
}
}
new Environment(process.env.npm_config_argv);
3.npm scriptを修正する
npm scriptに以下のコマンドを追加し、作成したscriptが実行されるようにします。
"scripts": {
...
"ionic:watch:before": "node ./scripts/environment",
"ionic:build:before": "node ./scripts/environment",
...
}
ionic serve
もしくはionic build
をすると、./src/app/app.config.ts.
が生成されるようになります。
また、ionic serve --prod --env=production
のようにパラメーターを渡すことで環境を切り替えることができます。
4.moduleにimportする
app.config.ts
をapp.module.ts
でimportします。
import { APP_CONFIG, AppConfig } from './app.config';
@NgModule({
...
providers: [
...
{ provide: APP_CONFIG, useValue: AppConfig }
...
]
})
5.読み込んで使用する
importすること、Angular DI経由で、app.config.ts
に設定された各種値を読み込めるようになります。
import { Component, Inject } from '@angular/core';
import { APP_CONFIG } from './app.config';
@Component({
selector: 'example-page',
templateUrl: 'example-page.html'
})
export class ExamplePage {
constructor(@Inject(APP_CONFIG) private config) {
console.log(config.environment);
console.log(config.endpoints.server1);
}
}
<参考>
https://github.com/ionic-team/ionic-app-scripts/issues/762#issuecomment-295235407
https://gist.github.com/rossholdway/16724496806b66a162ee6cbf8bfc5def