ionic3 构建项目自动匹配参数

1. src目录下创建env目录,并添加env.dev.ts,env.prod.ts,env.test.ts,可以根据自己需求添加。

env.dev.ts:

export class ENV {
  public static SERVER_API_URL = "http://192.168.2.100/api/v1/";
}

env.prod.ts:

export class ENV {
  public static SERVER_API_URL = "https://api.domain.com/api/v1/";
}

env.test.ts:

export class ENV {
  public static SERVER_API_URL = "http://testapi.domain.com/api/v1/";
}
2. 修改tsconfig.json文件,添加path
"compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@app/env": [
        "env/env.dev"
      ]
    }
  }

3. src目录下添加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.IONIC_ENV;
var mode = process.env.npm_config_mode;

useDefaultConfig.prod.resolve.alias = {
  "@app/env": path.resolve(environmentPath('prod'))
};

useDefaultConfig.dev.resolve.alias = {
  "@app/env": path.resolve(environmentPath('dev'))
};

if (env !== 'prod' && env !== 'dev') {
  // Default to dev config
  useDefaultConfig[env] = useDefaultConfig.dev;
  useDefaultConfig[env].resolve.alias = {
    "@app/env": path.resolve(environmentPath('dev'))
  };
}

if (mode == "test") {
  console.log("########### now we are building test version ###########");
}

function environmentPath(env) {
  if (mode) env = mode;    // for test build
  var filePath = './src/env/env.' + env + '.ts';
  if (!fs.existsSync(filePath)) {
    console.log(chalk.red('\n' + filePath + ' does not exist!'));
  } else {
    return filePath;
  }
}

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

4. package.json中添加webpack配置

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

5. ts文件中使用env变量

import { ENV } from "@app/env";

// sample usage
http.get(ENV.SERVER_API_URL);

6. 编译不同版本

dev:
ionic cordova build ios
prod:
ionic cordova build ios --prod
test:
ionic cordova build ios --mode=test

备注:

如果编译prod版本时报错,heap size不足,可以使用以下命令:

node --max-old-space-size=4096 $(which ionic) cordova build ios --prod

你可能感兴趣的:(ionic)