Skip to content

Instantly share code, notes, and snippets.

@rossholdway
Last active January 5, 2021 21:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossholdway/16724496806b66a162ee6cbf8bfc5def to your computer and use it in GitHub Desktop.
Save rossholdway/16724496806b66a162ee6cbf8bfc5def to your computer and use it in GitHub Desktop.
A script to run before the ionic build process that generates an app.config.ts file based off of a .env/{environment}.json file. See this comment for more info: https://github.com/ionic-team/ionic-app-scripts/issues/762#issuecomment-295235407
#!/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 { OpaqueToken } from "@angular/core"; //Use InjectionToken in Angular 4.x
export let APP_CONFIG = new OpaqueToken("app.config");
export const AppConfig = ${JSON.stringify(config)};
`);
wstream.end();
}
}
new Environment(process.env.npm_config_argv);
@rossholdway
Copy link
Author

The flag should contain an = sign e.g.--env=[environment] to work with latest Ionic CLI / Cordova build command. The script above has been updated to support this.

@JWesorick
Copy link

I'm getting
The config file for this environment is missing (Cannot find module '../env/--env.json')
when running ionic serve --env=[production].
What am I doing wrong?

@rossholdway
Copy link
Author

rossholdway commented Apr 21, 2017

@JWesorick Yes, I'm seeing this also. Ionic serve and Ionic build commands seem to split the arguments into an array differently. I'll add a fix for this and update.

@kukukk
Copy link

kukukk commented Apr 30, 2017

Hi,

It's enough to just check if (args.includes('ionic:build')). If it's true, do as you do know. If it's false, do as you did initially.
One more thing: I had to use path.resolve() to generate the final path for the url, otherwise is was not working for me.

Best regards,
kukukk

@gabrielalack
Copy link

This contructor works for serve / build for me using --env=whatever


constructor(args) {
    args = JSON.parse(args).original;
	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) : 'development';
	} else {
		let index = args.indexOf('--env');
		if(index === -1 ) {
			env = 'development';
		} else {
			env = args[index+1];
		}
	}
	console.log('\x1b[33m%s\x1b[0m', 'Using Environment Config: ', env);
    this.setEnvironment(env);
  }

@JWesorick
Copy link

As another option, I changed my constructor to use environment variables.

constructor(args) {
    let env = (process.env.NODE_ENV !== undefined) ? process.env.NODE_ENV : 'development'; //else set default
    this.setEnvironment(env);
  }

@rossholdway
Copy link
Author

@kukukk @gabrielalack @JWesorick Thanks for the comments 👍

I've updated the script to use args.includes('ionic:build') and added path.resolve() too.

@sklink
Copy link

sklink commented Sep 5, 2017

Hey @rossholdway,

Thanks for the code, it worked quite well for the default environment. However, I'm having troubles getting the --env= parameter to work when running ionic serve or build. It always defaults to development. I've tried logging process.env and process.argv to check to see whether the parameter was available elsewhere but had no luck.

Here's what I ran:

ionic serve --env=staging

Here are my scripts:

    "ionic": "./node_modules/.bin/ionic",
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "ionic:build:before": "node ./scripts/environment",
    "ionic:build": "ionic-app-scripts build",
    "ionic:watch:before": "node ./scripts/environment",
    "ionic:serve": "ionic-app-scripts serve"

Any suggestions?

Update

I was able to access the environment variable by adding it directly to "ionic:watch:before": "node ./scripts/environment --env=staging" but outside of that I've been unable to access that.

@rossholdway
Copy link
Author

@sklink Thanks for the update.

I've also recently discovered this and I think it's been caused by upgrading ionic cli / app scripts. Your update sounds like a good workaround, thanks.

I'll look into getting this working again with the --env= flag directly.

@prupp
Copy link

prupp commented Nov 2, 2017

@rossholdway any updates on this? Did you get this working again with the --env= flag?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment