ionic3 中使用 environments

1,112 阅读6分钟
原文链接: segmentfault.com
我们需要不同的环境下,需要不同的参数,比如后端api接口什么的,使用Angular Cli,可以很容易的实现这点。在ionic3中,与angular中不一样的,还有cordova这一层壳。

假设我们需要3个环境:devuatprod

web

  • IONIC_ENV: dev、prod,代表2种打包模式(简单说为aot与非aot)。
  • NODE_ENV: dev、uat、prod,代表3中不同的环境,webapp使用的参数。比如后端server_url不一样。cordova而言,比如jpush的key不一样。

区分这两种概念之后,就可以理解下面的组合了。

NODE_ENVIONIC_ENV的组合:

  1. dev dev: environments: environment.dev.ts , 非aot方式打包
  2. dev prod: environments: environment.dev.ts , aot方式打包
  3. uat dev: environments: environment.uat.ts , 非aot方式打包
  4. uat prod: environments: environment.uat.ts , 非aot方式打包
  5. prod dev: environments: environment.prod.ts , 非aot方式打包
  6. prod prod: environments: environment.prod.ts , 非aot方式打包

第一步: 在src目录下新建environments文件夹

增加environment.dev.ts,environment.uat.ts,environment.prod.ts

// environment.dev.ts
export const ENV = {
  "mode": "Dev",
  "database": "data.db",
  "server_url": "https://xxxx.com",
  "cordova":{
    "id":"io.ionic.starter.dev",
    "version":"0.0.1",
    "ios":{
      "CodePushServerUrl": "dev",
      "CodePushDeploymentKey":"1234567890"
    },
    "android":{
      "CodePushServerUrl": "dev",
      "CodePushDeploymentKey":"0987654321"
    }
  }
}

第二步: 修改 tsconfig.json

{
  "compilerOptions": {
    ...
    "baseUrl": "./src",
    "paths": {
      "@env/environment": [ "environments/environment.prod"]
    },
    ...
  },

第三步: 增加 config/webpack.config.js 文件

var chalk = require("chalk");
var fs = require('fs');
var path = require('path');
var useDefaultConfig = require('@ionic/app-scripts/config/webpack.config.js');

var env = process.env.NODE_ENV || 'dev';
var IONIC_ENV = process.env.IONIC_ENV

console.log('NODE_ENV:'+ env);

console.log('IONIC_ENV:'+IONIC_ENV);

if(env === 'dev'){
  if(IONIC_ENV == 'dev'){
    useDefaultConfig.dev.resolve.alias = {
      "@env/environment": path.resolve(environmentPath('dev'))
    };
  };
  if(IONIC_ENV == 'prod'){
    useDefaultConfig.prod.resolve.alias = {
      "@env/environment": path.resolve(environmentPath('dev'))
    };
  };
}

if(env === 'uat'){
  if(IONIC_ENV == 'dev'){
    useDefaultConfig.dev.resolve.alias = {
      "@env/environment": path.resolve(environmentPath('uat'))
    };
  };
  if(IONIC_ENV == 'prod'){
    useDefaultConfig.prod.resolve.alias = {
      "@env/environment": path.resolve(environmentPath('uat'))
    };
  };
}

if(env === 'prod'){
  if(IONIC_ENV == 'dev'){
    useDefaultConfig.dev.resolve.alias = {
      "@env/environment": path.resolve(environmentPath('prod'))
    };
  };
  if(IONIC_ENV == 'prod'){
    useDefaultConfig.prod.resolve.alias = {
      "@env/environment": path.resolve(environmentPath('prod'))
    };
  };
}

function environmentPath(env) {
  var filePath = 'src/environments/environment.' + env + '.ts';
  console.log("use env file:"+filePath);
  if (!fs.existsSync(filePath)) {
    console.log(chalk.red('\n' + filePath + ' does not exist!'));
  } else {
    return filePath;
  }
}

module.exports = function () {
  return useDefaultConfig;
};

第四步: 修改 package.json

增加config配置

  ....
  "config": {
    "ionic_webpack": "./config/webpack.config.js"
  }
  ....

使用方式

import { Component } from '@angular/core';
import {ENV} from '@env/environment'

@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html'
})
export class Page1Page {
  constructor() {
    console.log(ENV.mode);
  }
}

cordova

定义一个config.tpl.xml,使用hooks:before_prepare,在执行cordova prepare之前替换config.xml

第一步: 下载 es6-template-strings

npm install es6-template-strings --save-dev

第二步: 创建config/hooks/config.tpl.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="${id}" version="${version}" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>zoe</name>
    <description>An awesome Ionic app(zoe).</description>
    <author email="chenkai4dev@163.com" href="http://iszoe.com/">CK</author>
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <preference name="ScrollEnabled" value="false" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="300" />
    <preference name="SplashShowOnlyFirstTime" value="false" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="3000" />
    <hook src="config/hooks/before_prepare.js" type="before_prepare" />
    <platform name="android">
        <allow-intent href="market:*" />
        <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" />
        <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" />
        <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" />
        <icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png" />
        <icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png" />
        <icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png" />
        <splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png" />
        <splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png" />
        <splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png" />
        <splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png" />
        <splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png" />
        <splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png" />
        <splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png" />
        <splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png" />
        <splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png" />
        <splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png" />
        <splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png" />
        <splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
        <icon height="57" src="resources/ios/icon/icon.png" width="57" />
        <icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
        <icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
        <icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
        <icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
        <icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
        <icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
        <icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
        <icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
        <icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
        <icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
        <icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
        <icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
        <icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
        <icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
        <icon height="29" src="resources/ios/icon/icon-small.png" width="29" />
        <icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" />
        <icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" />
        <icon height="1024" src="resources/ios/icon/icon-1024.png" width="1024" />
        <splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
        <splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
        <splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
        <splash height="1242" src="resources/ios/splash/Default-Landscape-736h.png" width="2208" />
        <splash height="1536" src="resources/ios/splash/Default-Landscape@2x~ipad.png" width="2048" />
        <splash height="2048" src="resources/ios/splash/Default-Landscape@~ipadpro.png" width="2732" />
        <splash height="768" src="resources/ios/splash/Default-Landscape~ipad.png" width="1024" />
        <splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
        <splash height="2732" src="resources/ios/splash/Default-Portrait@~ipadpro.png" width="2048" />
        <splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
        <splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
        <splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
        <splash height="2732" src="resources/ios/splash/Default@2x~universal~anyany.png" width="2732" />
    </platform>
    <platform name="android">
        <preference name="CodePushDeploymentKey" value="${android.CodePushDeploymentKey}" />
    </platform>
    <platform name="ios">
        <preference name="CodePushDeploymentKey" value="${ios.CodePushDeploymentKey}" />
    </platform>
    <plugin name="cordova-plugin-whitelist" spec="1.3.3" />
    <plugin name="cordova-plugin-device" spec="2.0.1" />
    <plugin name="cordova-plugin-splashscreen" spec="5.0.2" />
    <plugin name="cordova-plugin-ionic-webview" spec="1.1.16" />
    <plugin name="cordova-plugin-ionic-keyboard" spec="2.0.5" />
    <plugin name="cordova-plugin-code-push" spec="1.11.7" />
    <engine name="ios" spec="4.5.4" />
    <engine name="android" spec="7.1.0" />
</widget>

第三步: 创建config/hooks/before_prepare.js

#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var compile = require('es6-template-strings/compile');
var resolveToString = require('es6-template-strings/resolve-to-string');

var ROOT_DIR = path.resolve(__dirname, '../../')

var env = process.env.NODE_ENV || 'dev';
var envFile = 'src/environments/environment.' + env + '.ts';

var FILES = {
  SRC: "config/hooks/config.tpl.xml",
  DEST: "config.xml"
};

console.log('hooks-start: before_prepare','envFile:'+envFile);

var srcFileFull = path.join(ROOT_DIR, FILES.SRC);
var destFileFull = path.join(ROOT_DIR, FILES.DEST);
var configFileFull = path.join(ROOT_DIR, envFile);

var templateData = fs.readFileSync(srcFileFull, 'utf8');
var configData = fs.readFileSync(configFileFull, 'utf8').toString().split('ENV =')[1];
var config = JSON.parse(configData)['cordova'];

var compiled = compile(templateData);
var content = resolveToString(compiled, config);

fs.writeFileSync(destFileFull, content);

console.log('hooks-end: before_prepare');

第四步,修改现有config.xml

增加<hook src="config/hooks/before_prepare.js" type="before_prepare" />

<?xml version='1.0' encoding='utf-8'?>
<widget id="io.ionic.starter" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>zoe</name>
    <description>An awesome Ionic app(zoe).</description>
    <author email="chenkai4dev@163.com" href="http://iszoe.com/">CK</author>
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <preference name="ScrollEnabled" value="false" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="300" />
    <preference name="SplashShowOnlyFirstTime" value="false" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="3000" />
  +  <hook src="config/hooks/before_prepare.js" type="before_prepare" />
  ....

命令

uat为例:

  "serve:uat":  "NODE_ENV=uat ionic build"
  "prepare:uat:prod": "NODE_ENV=uat ionic cordova prepare --prod",
  "build:ios:uat:prod": "NODE_ENV=uat ionic cordova build ios --prod",
  "build:android:uat:prod": "NODE_ENV=uat ionic cordova build android --prod"

示例