Ionic 2 Environment Variables: As simple as possible

Hey all,

One of the things I struggled with getting back into Ionic 2 was setting up environment variables. I couldn’t find an elegant solution anywhere, so I created my own:

Only one line is added to Ionic’s Webpack config, after that we create a single reusable module that will detect which environment we’re in by checking for the --prod flag when running Ionic. Alternatively, if you need more than ‘dev’ and ‘prod’, like a ‘qa’ environment, we can check Node’s NODE_ENV instead.

All that is covered in the tutorial. Let me know if you have any questions or suggestions.



Hi Rob,

thanks a lot for sharing your idea. I read your blog post but one line I do not understand:

useValue: process.env.IONIC_ENV === 'prod' ? prodVariables : devVariables

In the EnvironmentsModule you use process.env.IONIC_ENV, but is this not only available within the build-scripts?

Thanks, Rudolf

1 Like

Good question. Normally you are exactly right, IONIC_ENV is only available on the server side in the build scripts. That’s why we need to set the Webpack Environment Plugin to look for ‘IONIC_ENV’: new webpack.EnvironmentPlugin(['IONIC_ENV']).

When Webpack builds your code, that plugin tells it to replace any occurrence of process.env.IONIC_ENV in the front-end code with the value.

Hi Rob,

thank a lot for your instant reply!
Now everything is clear.

Have you seen this

Hopefully Ionic will soon have an solution for this.


1 Like

No problem :slight_smile:

Yep, there’s a lot of proposals like that floating around, that one I don’t really like as written because it is just doing a find replace on any key / value pair based on what’s in package.json. Another commenter on there though proposes a better solution where you can just specify a different file per environment in package.json.

We may well get a solution like that in the future, but until then this is the best solution I’ve found. And this should be backwards compatible even if a feature like this is implemented.

1 Like