Feature request: Ionic 2 (dev/prod) environment variables configuration
From @amreladawy on July 24, 2016 6:58
Short description of the problem:
It is a feature request. Just like Angular2, I hope that Ionic can provide 2 files (environment.dev.ts and environment.prod.ts) that would contain variables with different values corresponding to production and development environment. During the build, the appropriate file to be copied and bundled within the app artifact.
Which Ionic Version? 2.x
https://forum.ionicframework.com/t/ionic-2-environment-variables-config-setup/58147/1
https://stackoverflow.com/questions/36004810/how-to-config-different-development-environment-in-angular-2-app
Copied from original issue: driftyco/ionic#7413
Can we raise the priority for this issue? This is actually very important. Our app has different configs for prod and devel. Without this, it requires ugly hand rolled variable updates... Just make the release really cumbersome.
Currently our implementation uses the rollup-plugin-replace, and a slightly modified rollup config.
Basically what happens is that the import paths are replaced based on the process.env.IONIC_ENV variable during compile time. This will use the environment.dev.ts during development and environment.prod.ts when in production.
Implementation steps
-
install the rollup-plugin-replace
npm install --save-dev rollup-plugin-replace -
create two files;
environment.dev.tsandenvironment.prod.tswithin e.g. thesrc/configdirectory.
├── src/config/environment.dev.ts
export const ENV = {
PRODUCTION : false,
API_URL : 'dev.local'
};
├── src/config/environment.prod.ts
export const ENV = {
PRODUCTION : true,
API_URL : 'prod.local'
};
- import the
environment-devas the default within your pages / services etc.
// use the 'environment-dev' as the default import(!)
import { ENV } from '../../config/environment-dev';
@Component({
templateUrl: 'hello-ionic.html'
})
export class HelloIonicPage {
console.log( ENV.API_URL );
}
- update your
/package.json
├── /package.json
"config": {
"ionic_rollup": "./config/rollup.config.js"
}
- create your
rollup.config.jswithin the/configdirectory. Require the plugin, and add thereplacesnippet below to your plugins section. One can usenode_modules\@ionic\app-scripts\config\rollup.config.jsas a template.
├── /config/rollup.config.js
var replace = require('rollup-plugin-replace');
var isProd = (process.env.IONIC_ENV === 'prod');
...
plugins: [
replace({
exclude: 'node_modules/**',
// use the /config/environment-dev as the default import(!), no stub needed.
// note we only replace the "last" part of the import statement so relative paths are maintained
'/config/environment-dev' : ( isProd ? '/config/environment-prod' : '/config/environment-dev'),
})
...
]
Hope this helps someone! Of course in an ideal situation a file replacement would take place, similar to the Angular CLI
Is there any plans to actually implement this?
With "@ionic/app-scripts": "0.0.39" now defaulting to webpack for bundling, I am doing something like this.
Steps to implement:
-
Make sure you have installed the latest app-scripts
npm install @ionic/app-scripts@latestand have the latesttsconfig.json. -
Install dotenv.
-
Create
.envfile with env variables defined in the root directory of your app. Recommended: add.envto.gitignore. -
Create and modify
webpack.config.jsfrom original found here:
├── /config/webpack.config.js
require('dotenv').config();
...
function getPlugins() {
var plugins = [
new webpack.DefinePlugin({
'API_URL': JSON.stringify(process.env.API_URL)
// Add any more variables here that you wish to define
})
];
if (process.env.IONIC_ENV === 'prod') {
// This helps ensure the builds are consistent if source hasn't changed:
plugins.push(new webpack.optimize.OccurrenceOrderPlugin());
}
return plugins;
}
...
- Define custom webpack config file in
package.json.
├── /package.json
"config": {
"ionic_webpack": "./config/webpack.config.js"
}
- Create custom typings file defining the constants that are in your
.envfile so that webpack can populate them and you are able to reference them in your application.
├── /src/customTypings/customTypings.d.ts
declare var API_URL: string;
// Add any more variables here that you wish to define
You should now be able to reference the global variable(s) in your app.
Furthermore, you can create multiple .env files for different environments and require them in webpack.config.js like so:
require('dotenv').config({path: '/custom/path/to/your/env/vars'})
This solution is working, but I think, rewriting all webpack.config is not good, becase updates... Is there any idea from ionic team?
@jgw96 Can we get this added to a milestone? We should be able to specify different environment configuration e.g. different API endpoints for dev and production. As @slinto mentioned creating a modified webpack.config is not ideal as updates will cause issues :/
I'd really like to see this functionality supported. Is a custom webpack config the only way?
Okay... After a lot of coffee and head bumping, I've realized that the best way (at least for me) is to change the environments manually and not rely on ionic to change it. That was mainly because ionic-cli does not let you runionic serve with production environment.
I have set an environment.ts in the root folder of the app that contains all the variables.
environment.ts
export class ENV {
public static currentEnvironment: string = "development";
// public static currentEnvironment: string = "production";
public static development: any = {
key1: "value1",
key2: "value2",
......
......
};
public static production: any = {
key1: "value1",
key2: "value2",
......
......
};
}
Then I added an environment.service among my services.
environment.service.ts
import {Injectable} from '@angular/core';
import {ENV} from '../../environments/environment';
@Injectable()
export class EnvironmentService {
public getKey1() : string{
if(ENV.currentEnvironment === "development"){
return ENV.development.key1;
} else if(ENV.currentEnvironment === "production") {
return ENV.production.key1;
}
}
public getKey2() : string{
if(ENV.currentEnvironment === "development"){
return ENV.development.key2;
} else if(ENV.currentEnvironment === "production") {
return ENV.production.key2;
}
}
......
......
}
Then I added the service to the providers of the app.module and used it like any other service. E.g. in any component you can access the values like this:
any.component.ts
...
...
...
import {EnvironmentService} from '../../services/environment.service';
...
...
...
constructor(
...
...
...
private environmentService: EnvironmentService
...
...
...) {
}
...
...
...
let baseUrl = this.environmentService.getKey1();
...
...
...
And finally, in order to change the environment, you have to toggle (comment and uncomment) the first two line of environment.ts.
This is a good workaround for now, if you need different values (URLs, API keys, etc.) to be used in development and production. But, I think eventually, ionic and ionic-cli teams will have to work together to integrate something like this internally, that lets us use different sets of environment variables based on a flag that we pass to the command that is running the app. E.g. : ionic (serve/run) (--prod/--dev)
hmm, the manual comment/uncomment of right ENV is dangerous, because is there a big risk with publishing application with development environment to store, especially if your team is about 1+ people :) I think about right way as:
ionic serve / DEVELOPMENT ENV (DEFAULT):
$ ionic serve
ionic serve / PRODUCTION or CUSTOM ENV:
$ ionic serve --env=prod,
$ ionic serve --env=test,
$ ionic serve --prod
ionic build / PRODUCTION ENV (DEFAULT):
$ ionic build
ionic build / DEVELOPMENT or CUSTOM ENV:
$ ionic build --dev
$ ionic build --env=test
$ ionic build --env=dev
eg. http://jonnyreeves.co.uk/2016/simple-webpack-prod-and-dev-config/
@slinto You are absolutely correct, there is the possibility of publishing the app with dev variables. But, it is only as dangerous as any other solution. You may build the prod app with the wrong command as well. I'm actually using this in a corporate project with a big number of people on the team. I think nowadays every team uses version control systems like git or svn. So, this would be just a matter of team functionality and team members being coordinated with each other. And furthermore, there is usually only one person in team who is in charge of deploying the app. But, again, you're right. With manual toggle of environments, there is a slightly higher chance of making the mistake. So, as I said, this is only a temporary fix. Ideally, this should be internal to ionic, using the commands you mentioned.
+1
Hey, guys, any progress of official implements?
@dnmd can you confirm that your solution works with a production build?
with 0.0.46 adding anything at config in package.json trigger rollup warnings (and the script freeze after that)
[18:58:40] rollup: Conflicting namespaces: /space/www/applications/wav/node_modules/@angular/compiler/index.js
re-exports 'NgContentAst' from both
/space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js (will be
ignored) and /space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js.
[18:58:40] rollup: Conflicting namespaces: /space/www/applications/wav/node_modules/@angular/compiler/index.js
re-exports 'PropertyBindingType' from both
/space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js (will be
ignored) and /space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js.
[18:58:40] rollup: Conflicting namespaces: /space/www/applications/wav/node_modules/@angular/compiler/index.js
re-exports 'templateVisitAll' from both
/space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js (will be
ignored) and /space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js.
By the way, isn't it better to listen for the argument --release ?
Another thing, why with 0.0.46 it's rollup and not webpack by default?
I like the idea of @slinto In our case, we have actually 5 environments...
- dev
- test (unit test)
- iat (human first line test => developer tester)
- uat (human second line test => business client tester)
- prod
And we have to copy config file at build time to choose the environment.
To chose the environment at build time, we run it like :
TARGET=xxx ionic run yyy for mac or set TARGET=xxx&& ionic run yyy for windows developer.
This is managed by a hook based on this post : http://www.kdmooreconsulting.com/blogs/build-a-cordova-hook-to-setup-environment-specific-constants/
But since we do that, we lost the live reload feature! (ionic-app-script watch doesn't copy our right config.js file and we don't know how to do that).
If we can set a parameter like @slinto told -- to choose the environment with something like "--env=xxx", and make it available for live reload ... -- it will be really cool!
Definitely a must. So +1
So how would this tie in with the Live Deploy to channel feature currently available https://docs.ionic.io/services/deploy/ ?
OK, so I needed this kind of feature to be able to have different parameters (api endpoints, google analytics ID etc...) with different environments (dev, preprod, prod...).
So I made my first module (feedbacks more than welcome, and please be gentle :p) to be able to do that: gl-ionic2-env-configuration
Basically, it loads a env-configuration.json located in the www folder before anything else (so that your api url will be set even in your apiService constructor, for example).
In the package documentation, I linked a simple node executable to easily copy the configuration file for a specific environment.
Advantages
- You don't need to override the Ionic webpack.config (which could break things when Ionic updates).
- You can have as much environments as you want and name it as you like.
- You can dynamically change the configuration file without having to recompile the app (which will be very useful for continous integration systems).
Hope this will help.
Any updates to this Ionic team? I would love to see this baked into the ionic-app-scripts repo.
Inspired by the solution from @tabirkeland I thought I'd post my own version of this. The differences with the script below vs the original solution:
- The Ionic
webpack.configscript is built upon, not replaced, meaning that any updates to@ionic/app-scriptsshould be merged in. - The script is aware of Ionic's
--prodflag, allowing you to provide separate configuration fordevandprodbuilds. - There is no dependency on
dotenv.
Here's the steps to get it all working:
- Create a file at
config/webpack.config.jsand paste the following content:
// Set the `ENV` global variable to be used in the app.
var path = require('path');
var webpack = require('webpack');
var projectRootDir = process.env.IONIC_ROOT_DIR;
var appScriptsDir = process.env.IONIC_APP_SCRIPTS_DIR;
var config = require(path.join(appScriptsDir, 'config', 'webpack.config.js'));
var env = process.env.IONIC_ENV || 'dev';
var envVars;
try {
envVars = require(path.join(projectRootDir, 'env', env + '.json'));
} catch(e) {
envVars = {};
}
config.plugins = config.plugins || [];
config.plugins.push(
new webpack.DefinePlugin({
ENV: Object.assign(envVars, {
environment: JSON.stringify(env)
})
})
);
if(env === 'prod') {
// This helps ensure the builds are consistent if source hasn't changed:
config.plugins.push(new webpack.optimize.OccurrenceOrderPlugin());
}
module.exports = config;
- Add the following entry to your
package.json:
"config": {
"ionic_webpack": "./config/webpack.config.js"
}
- If you need additional configuration, create two files
env/dev.jsonandenv/prod.json. In here, put any configuration you need for that environment. Your json should be an object of key-value pairs, which will be made available for use in your application.
{
"enableLogging": true,
"apiServerUrl": "\"http://example.com/api\""
}
Now, you can use the ENV global constant anywhere in your .ts files:
declare const ENV;
if(ENV.environment === 'dev') {
// Run without the `--prod` flag.
// Any keys defined in `dev.json` will be available on the `ENV` object.
} else if (ENV.environment === 'prod') {
// Run with the `--prod` flag.
// Any keys defined in `prod.json` will be available on the `ENV` object.
}
The script creates an ENV object with a single key, environment, which is set to prod if you run your ionic command with the --prod flag. Otherwise, this will be dev.
The env/dev.json and env/prod.json files are optional. If present, the script will merge the appropriate object into ENV. The script above uses webpack's DefinePlugin, so remember to 'stringify' any string values, otherwise webpack will assume you want to insert a code fragment. For example:
{
"apiServerUrl": "\"http://example.com/api\""
}
It would be great to see this baked into the core webpack.config.js file in the app-scripts repo.