LoginSignup
4
5

More than 5 years have passed since last update.

ionicでenvironmentsを利用する。

Last updated at Posted at 2018-04-10

ionicではangularのenvironmentsのような環境ごとに変数を切り替える機能がデフォルトではないので、調べた中で一番シンプルそうな方法で実装してみようと思います。
(ionic4では実装されるらしい。)

1. 各環境用のjsonファイルを作成する

.envフォルダを作成し、環境毎にjsonファイルを作成します。

.env/
  production.json
  staging.json
  development.json

ファイルの中身は、以下のような内容にします。

development.json
{
  "environment": "development",
  "endpoints": {
    "server1": "https://....",
    "server2": "https://...."
  }
}

2.Scriptを作成する

上記jsonファイルを読み込み、app.config.tsファイルを生成するためのスクリプト、./scripts/environment.jsを作成します。

./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が実行されるようにします。

package.json
"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.tsapp.module.tsでimportします。

app.module.ts
import { APP_CONFIG, AppConfig } from './app.config';

@NgModule({
    ...
  providers: [
    ...
    { provide: APP_CONFIG, useValue: AppConfig }
    ...
  ]
})

5.読み込んで使用する

importすること、Angular DI経由で、app.config.tsに設定された各種値を読み込めるようになります。

example-page.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

4
5
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
5